﻿#include "StdAfx.h"
#include "LogAnalyze.h"


#include "Module.h"
#include "WebEngine.h"
#include "GetUSN.h"
#include "ParseWebResultFile.h"
#include "GetDnsRecord.h"
#include "ReadKernalResult.h"

#include "MD5Checksum.h"
#include "GetUserEnumName.h"
#include "GetAllLogCount.h"
#include <fstream>
#include <sstream>
#include <GetHostAsset.h>
#include <LMaccess.h> // 获取系统用户
#include <comdef.h>
#include <set>
#include <string>
#include <algorithm>
#include <CReadSource.h>
#include <NextCheckSec.h>
#include <LM.h>
#include <MySuspiciousFile.h>
std::vector<std::pair<CString, CString>>vtAccountLogin;	// 账户登录
std::vector<std::pair<CString, CString>>vtAccountManage;	// 账户管理
std::vector<std::pair<CString, CString>>vtDetailedTrace;	// 详细跟踪
std::vector<std::pair<CString, CString>>vtDSAccess;		// DS访问
std::vector<std::pair<CString, CString>>vtLoginLogout;	// 登录/注销
std::vector<std::pair<CString, CString>>vtObjectAccess;	// 对象访问
std::vector<std::pair<CString, CString>>vtPolicyChange;	// 策略更改
std::vector<std::pair<CString, CString>>vtPrivilegeUse;	// 特权使用
std::vector<std::pair<CString, CString>>vtSystem;			// 系统
std::vector<std::pair<CString,CString>> m_vecWindosStatistics;//windos需要统计的表
std::vector<std::pair<CString,CString>> m_vecAttackType;//web攻击
static std::vector<CString> KeyWords;

typedef struct
{
	CString strUserName;
	int  intExist;
}USERINFO ,*PUSERINFO;
typedef struct  
{
	CString strUserName;//被创建用户名
	CString strCreateUserName;//创建用户名
	int		intExist;
	CString strCreateTime;
	CString strHostIp;//主机IP
}SUSPICIOUSUSERINFO,*PSUSPICIOUSUSERINFO;//可疑账户信息
typedef struct  
{
	int attack_type;//攻击类型1--web攻击类型 2--主机攻击类型
	CString strattack_code;//攻击名对应code
	CString strattack_name;//攻击名
	CString attack_time;//攻击时间范围

}RESULTS_ATTACK_BEHAVIOR,*PRESULTS_ATTACK_BEHAVIOR;
/*
// windows 计划任务
typedef struct 
{
	CString TaskName;//任务名称
	CString Date;//创建时间
	CString Author;//创建者
	CString Description;//描述
	CString URI;//任务路径
	CString StartBoundary;//触发开始时间
	CString EndBoundary;//结束时间
	CString DaysInterval;//触发周期
	CString UserId;//用户ID
	CString Command;//启动内容
	CString	Enabled;//启动状态
	CString file_md5;//任务md5值

} TASKLIST ,*PTASKLIST;*/

/*
//补丁信息
typedef struct  
{
	CString Path_Num;//补丁序号
	CString Path_Name;//补丁名称
	CString Path_Program;//补丁程序
	CString Path_Version;//补丁版本
	CString Path_Publisher;//补丁发布者
	CString Path_InstallDate;//补丁安装时间
} PATHINFOLIST,*PPATHINFOLIST;
*/
/*
//用set容器时需要重向定义
bool operator<(const PATHINFOLIST & x,const PATHINFOLIST & y)
{

	return x.Path_Name<y.Path_Name;
}*/
// 文件深度
void CLogAnalyze::FileNeep(int type, std::vector<p_IpTimeRange_>&vt)
{
	if(CModule::m_bStop)
		return;

	CString DbPath = CTOOLBOX4App::ms_strFullResultPath;
	DbPath += _T("主机层\\hongtan004.db");

	CString mDisk = NULL;
	if(type == FASTGATHER)
	{
		TCHAR Drive[MAX_PATH] = {0};
		GetSystemDirectory(Drive, MAX_PATH);
		CString fPath(Drive);
		fPath = fPath.Left(1);
		mDisk = fPath;
	}
	else if(type == ALLDISKGATHER)
	{
		CString Disk = CPage4::m_strDisk;
		Disk.Remove(_T(':'));
		Disk.Remove(_T(';'));
		mDisk = Disk;
	}
	else if(type == CUSTOMGATHER)
	{
		CString Disk = CPage4::m_strSelDisk;
		Disk.Remove(_T(':'));
		Disk.Remove(_T(';'));
		mDisk = Disk;
	}
	CString Mac = CTOOLBOX4App::ms_strMacAddr;
	CString EventTaskId = CModule::m_csEventTaskId;
/*	vt.clear();
	p_IpTimeRange_ p_test;
	p_test = new IpTimeRange_;
	_tcscpy(p_test->IP, _T("10.10.10.10"));
	//_tcscpy(p_test->FirstTime, _T("2017-08-09 10:27:19"));
	//_tcscpy(p_test->LastTime, _T("2018-09-28 10:55:13"));
	_tcscpy(p_test->FirstTime, _T("2017-08-09 10:27:19"));
	_tcscpy(p_test->LastTime, _T("2020-01-10 10:55:13"));
	p_test->IpSource = _T('1');
	vt.push_back(p_test);*/
//	SuspicousFileNeep(DbPath.GetBuffer(), mDisk.GetBuffer(), vt, Mac.GetBuffer(), EventTaskId.GetBuffer());
}


//#pragma  comment(lib, "SecLogInsert.lib")

std::vector<PSYSTEMLOGINFO> CLogAnalyze::m_vSecurityLog;
std::vector<CString> CLogAnalyze::m_vIP;
std::vector<p_CreateProcess> CLogAnalyze::m_v4688Log;
std::vector<p_CreateProcess> CLogAnalyze::m_vCMDlog;
std::vector<p_ExitProcess> CLogAnalyze::m_v4689Log;
std::vector<PSYSTEMLOGINFO> CLogAnalyze::m_vSecurity0_4;
std::vector<PSYSTEMLOGINFO> CLogAnalyze::m_vLogin_4624;
std::vector<PSYSTEMLOGINFO> CLogAnalyze::m_vLogin_4648;
std::vector<p_UserLogin_4624> CLogAnalyze::m_vfLogin_4624;
std::vector<p_UserLogin_4648> CLogAnalyze::m_vfLogin_4648;
std::vector<p_CreateProcess> CLogAnalyze::m_vCrtPrcs0_4;
std::vector<std::vector<std::pair<CString, CString>>> CLogAnalyze::m_vLog_5156;
std::vector<std::vector<std::pair<CString, CString>>> CLogAnalyze::m_vLog_5157;
std::vector<std::vector<std::pair<CString, CString>>> CLogAnalyze::m_vLog_5158;
std::vector<std::vector<std::pair<CString, CString>>> CLogAnalyze::m_vLog_5152;
std::vector<std::vector<std::pair<CString, CString>>> CLogAnalyze::m_vLog_5153;
std::vector<p_FiltratedIP> CLogAnalyze::m_vfIP;


CLogAnalyze::CLogAnalyze(void)
{
	KeyWords.clear();
	KeyWords.push_back(_T("%drop table%"));
	KeyWords.push_back(_T("%drop function%"));
	KeyWords.push_back(_T("%lock tables%"));
	KeyWords.push_back(_T("%unlock tables%"));
	KeyWords.push_back(_T("%load_file()%"));
	KeyWords.push_back(_T("%into outfile%"));
	KeyWords.push_back(_T("%into dumpfile%"));
	KeyWords.push_back(_T("%select * from%"));
	KeyWords.push_back(_T("%show databases%"));
	m_vecWindosStatistics.clear();

	m_vecWindosStatistics.push_back(std::pair<CString,CString>(_T("Sec_Base_Line"),_T("c997a91adda74d9a8a2191664d955003")));//表格名对应的analysis_config_id ---安全基线
	m_vecWindosStatistics.push_back(std::pair<CString,CString>(_T("Sys_Port_Info"),_T("c997a91adda74d9a8a2191664d955004")));//表格名对应的analysis_config_id ---网络连接
	m_vecWindosStatistics.push_back(std::pair<CString,CString>(_T("Service"),_T("c997a91adda74d9a8a2191664d955005")));//表格名对应的analysis_config_id ---服务
	m_vecWindosStatistics.push_back(std::pair<CString,CString>(_T("Process"),_T("c997a91adda74d9a8a2191664d955006")));//表格名对应的analysis_config_id ---进程
	m_vecWindosStatistics.push_back(std::pair<CString,CString>(_T("Net_Light_Check"),_T("c997a91adda74d9a8a2191664d955007")));//表格名对应的analysis_config_id ---联网痕迹
	m_vecWindosStatistics.push_back(std::pair<CString,CString>(_T("Usb_Light"),_T("c997a91adda74d9a8a2191664d955008")));//表格名对应的analysis_config_id ---介质使用
	m_vecWindosStatistics.push_back(std::pair<CString,CString>(_T("Key_Software"),_T("c997a91adda74d9a8a2191664d955011")));//表格名对应的analysis_config_id ---关键软件
	//	m_vecWindosStatistics.push_back(pair<CString,CString>(_T("Sec_Base_Line"),_T("c997a91adda74d9a8a2191664d955015")));//表格名对应的analysis_config_id ---内核
	m_vecAttackType.clear();//文件名对应的攻击类型
	m_vecAttackType.push_back(std::pair<CString,CString>(_T("file_include"),_T("c997a91adda74d9a8a2191664d955019")));			//任意文件读取
	m_vecAttackType.push_back(std::pair<CString,CString>(_T("http_crlf"),_T("c997a91adda74d9a8a2191664d955025")));			//CRLF HTTP协议头操纵
	m_vecAttackType.push_back(std::pair<CString,CString>(_T("java_ouin_stream"),_T("c997a91adda74d9a8a2191664d955022")));//JAVA反序列化攻击
	m_vecAttackType.push_back(std::pair<CString,CString>(_T("passwd_attack"),_T("c997a91adda74d9a8a2191664d955023")));		//密码验证码暴力破解
	m_vecAttackType.push_back(std::pair<CString,CString>(_T("scan_robots"),_T("c997a91adda74d9a8a2191664d955020")));		//扫描器入侵行为
	m_vecAttackType.push_back(std::pair<CString,CString>(_T("sensitive_file"),_T("c997a91adda74d9a8a2191664d955026")));	//敏感文件访问
	m_vecAttackType.push_back(std::pair<CString,CString>(_T("shell_shock"),_T("c997a91adda74d9a8a2191664d955024")));			//Shellshock破壳命令注入
	m_vecAttackType.push_back(std::pair<CString,CString>(_T("sql_injection"),_T("c997a91adda74d9a8a2191664d955017")));		//SQL注入
	m_vecAttackType.push_back(std::pair<CString,CString>(_T("webshell"),_T("c997a91adda74d9a8a2191664d955028")));			//Webshell
	m_vecAttackType.push_back(std::pair<CString,CString>(_T("xss"),_T("c997a91adda74d9a8a2191664d955018")));					//XSS攻击
	m_vecAttackType.push_back(std::pair<CString,CString>(_T("struts2_remote_command_exe"),_T("c997a91adda74d9a8a2191664d955021")));	//	Struts2远程命令执行	
	m_vecAttackType.push_back(std::pair<CString,CString>(_T("struts2_attack"),_T("c997a91adda74d9a8a2191664d955035")));	//Struts2威胁攻击检测				
	m_vecAttackType.push_back(std::pair<CString,CString>(_T("urljump"),_T("c997a91adda74d9a8a2191664d955034")));	//域名跳转		
	m_vecAttackType.push_back(std::pair<CString,CString>(_T("command_execution"),_T("c997a91adda74d9a8a2191664d955036")));	//命令行攻击	
}


CLogAnalyze::~CLogAnalyze(void)
{
}

void SusAccount(sqlite3 *db);
bool operator<(const SUSPICIOUSUSERINFO & x,const SUSPICIOUSUSERINFO & y)
{

	return x.strUserName<y.strUserName;
}
// WCHAR* 转 string
void Wchar_tToString(std::string& szDst, wchar_t *wchar)
{
	wchar_t * wText = wchar;
	DWORD dwNum = WideCharToMultiByte(CP_OEMCP,NULL,wText,-1,NULL,0,NULL,FALSE);// WideCharToMultiByte的运用
	char *psText; // psText为char*的临时数组，作为赋值给std::string的中间变量
	psText = new char[dwNum];
	WideCharToMultiByte (CP_OEMCP,NULL,wText,-1,psText,dwNum,NULL,FALSE);// WideCharToMultiByte的再次运用
	szDst = psText;// std::string赋值
	delete []psText;// psText的清除
}

#if 0  // 不用了

// 获取IP地址(IPv4和IPv6)
void CLogAnalyze::GetIPAddr()
{
	string str;
	vector<PSECURITYLOGINFO>:: iterator it;
	for(it = m_vSecurityLog.begin(); it != m_vSecurityLog.end(); it++)
	{
		Wchar_tToString(str, (*it)->describe);
		
		smatch sm;
		// IPv4正则
		//regex reg("地址:\\t((1\\d{2}|25[0-5]|2[0-4]\\d|[1-9]?\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)");
		// 可以匹配IPv4和IPv6
		regex reg("地址:(\\t)+[a-zA-Z:\\.0-9]*\\|");
		// 匹配所有
		for(sregex_iterator it(str.begin(),str.end(),reg),end;it != end;it++)
		{
			// Ip= "地址:	127.1.0.1|"
			CString Ip((*it).str().c_str());
			Ip.Remove(_T('\t'));
			Ip.Remove(_T('|'));
			Ip = Ip.Mid(Ip.Find(_T(':'))+1);
			//AfxMessageBox(Ip);
			//vt.push_back(Ip);
			m_vIP.push_back(Ip);
		}
	}

	// 排序后去除重复元素
	sort(m_vIP.begin(), m_vIP.end());
	m_vIP.erase(unique(m_vIP.begin(), m_vIP.end()), m_vIP.end());
	// 去除多余的容量
	vector<CString>(m_vIP).swap(m_vIP);
	//vector<CString>::iterator it1;
	//for(it1 = m_vIP.begin(); it1 != m_vIP.end(); it1++)
	//{
	//	AfxMessageBox(*it1);
	//}
}

// 清空存放4688日志的容器
void My4688VtClear(vector<p_CreateProcess>&vt)
{
	if(vt.empty())
		return;
	vector<p_CreateProcess>::iterator it = vt.begin();
	for(; it != vt.end(); it++)
	{
		if(*it != NULL)
		{
			delete (*it);
			*it = NULL;
		}
	}
	vt.clear();
}
// 清空存放安全日志的容器
void MySecurityVtClear(vector<PSECURITYLOGINFO>&vt)
{
	if(vt.empty())
		return;
	vector<PSECURITYLOGINFO>::iterator it;
	for(it = vt.begin(); it != vt.end(); it++)
	{
		if(*it != NULL)
		{
			delete *it;
			*it = NULL;
		}
	}
	vt.clear();
}

// 将日志描述信息 拆分出来
void Translate4688(PSECURITYLOGINFO pLog, p_CreateProcess p4688)
{
	if(pLog == NULL || p4688 == NULL)
		return;
	memset(p4688, 0, sizeof(_CreateProcess));

	memcpy(p4688->event_level, pLog->event_level, sizeof(p4688->event_level));
	memcpy(p4688->date, pLog->date, sizeof(p4688->date));
	memcpy(p4688->source, pLog->source, sizeof(p4688->source));
	memcpy(p4688->event_id, pLog->event_id, sizeof(p4688->event_id));
	memcpy(p4688->task_type, pLog->task_type, sizeof(p4688->task_type));

	CString desc(pLog->describe);
	CString sub = desc.Mid(desc.Find(_T("|"))+1);
	sub = sub.Mid(sub.Find(_T("|"))+1);
	CString dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4688->Cr_security_ID, dest);	// 安全ID
	sub = sub.Mid(sub.Find(_T("|"))+1);
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4688->Cr_account_name, dest);	// 账户名
	sub = sub.Mid(sub.Find(_T("|"))+1);
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4688->Cr_account_region, dest);	// 账户域
	sub = sub.Mid(sub.Find(_T("|"))+1);
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4688->Cr_LoginID, dest);		// 登录ID
	sub = sub.Mid(sub.Find(_T("|"))+1);
	sub = sub.Mid(sub.Find(_T("|"))+1); //跳过"目标主题"
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4688->Tg_security_ID, dest);	// 安全ID
	sub = sub.Mid(sub.Find(_T("|"))+1);
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4688->Tg_account_name, dest);	// 账户名
	sub = sub.Mid(sub.Find(_T("|"))+1);
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4688->Tg_account_region, dest);	// 账户域
	sub = sub.Mid(sub.Find(_T("|"))+1);
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4688->Tg_loginID, dest);		// 登录ID
	sub = sub.Mid(sub.Find(_T("|"))+1);
	sub = sub.Mid(sub.Find(_T("|"))+1);//跳过"进程信息"
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4688->New_processID, dest);		// 新进程ID
	sub = sub.Mid(sub.Find(_T("|"))+1);
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4688->New_processName, dest);	// 新进程名称
	sub = sub.Mid(sub.Find(_T("|"))+1);
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4688->token_type, dest);		// 令牌提升类型
	sub = sub.Mid(sub.Find(_T("|"))+1);
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4688->Mandatory_Label, dest);	// 强制性标签
	sub = sub.Mid(sub.Find(_T("|"))+1);
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4688->creator_processID, dest);	// 创建者进程ID
	sub = sub.Mid(sub.Find(_T("|"))+1);
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4688->creator_processName, dest);	// 创建者进程名称
}

void CLogAnalyze::Get_4688_Log()
{
	My4688VtClear(m_v4688Log);
	vector<PSECURITYLOGINFO>::iterator it = m_vSecurityLog.begin();
	for(; it != m_vSecurityLog.end(); it++)
	{
		CString str((*it)->event_id);
		if(str.Compare(_T("4688")) == 0)
		{
			p_CreateProcess p_Crtprs;
			p_Crtprs = new _CreateProcess;
			memset(p_Crtprs, 0, sizeof(_CreateProcess));
			//MyIntBox(sizeof(p_Crtprs->event_level));
	
			Translate4688(*it, p_Crtprs);
			m_v4688Log.push_back(p_Crtprs);
		}
	}
	return ;
}

void CLogAnalyze::Get_CreateCMD_Log()
{
	My4688VtClear(m_vCMDlog);
	vector<p_CreateProcess>::iterator it = m_v4688Log.begin();
	for(; it != m_v4688Log.end(); it++)
	{
		CString NewProcessName((*it)->New_processName);
		// 从"C:\Windows\SysWOW64\cmd.exe" 对比 cmd.exe
		if(NewProcessName.Mid(NewProcessName.ReverseFind(_T('\\'))+1) == _T("cmd.exe"))
		{
			p_CreateProcess cp = new _CreateProcess;
			memset(cp, 0, sizeof(_CreateProcess));
			memcpy(cp, (*it), sizeof(_CreateProcess));
			m_vCMDlog.push_back(cp);
		}
	}
	//My4688VtClear(m_v4688Log);
}

void CLogAnalyze::Get_4689_log()
{
	vector<PSECURITYLOGINFO>::iterator it = m_vSecurityLog.begin();
	for(; it != m_vSecurityLog.end(); it++)
	{
		//if((*it)->event_id )
		if(_tcscmp((*it)->event_id, _T("4689")) == 0)
		{
			//AfxMessageBox((*it)->describe);
			p_ExitProcess pep = new _ExitProcess;
			if(pep != NULL)
				memset(pep, 0, sizeof(_ExitProcess));
			memcpy(pep->event_level, (*it)->event_level, sizeof(pep->event_level));
			memcpy(pep->date, (*it)->date, sizeof(pep->date));
			memcpy(pep->source, (*it)->source, sizeof(pep->source));
			memcpy(pep->event_id, (*it)->event_id, sizeof(pep->event_id));
			memcpy(pep->task_type, (*it)->task_type, sizeof(pep->task_type));

			CString desc((*it)->describe);
			desc = desc.Mid(desc.Find(_T("|"))+1);
			desc = desc.Mid(desc.Find(_T("|"))+1);
			CString sub = desc.Left(desc.Find(_T("|")));
			sub.Remove(_T('\t'));
			sub = sub.Mid(sub.Find(_T(":"))+1);
			_tcscpy(pep->Security_ID, sub);			// 安全ID
			desc = desc.Mid(desc.Find(_T("|"))+1);
			sub = desc.Left(desc.Find(_T("|")));
			sub.Remove(_T('\t'));
			sub = sub.Mid(sub.Find(_T(":"))+1);
			_tcscpy(pep->Account_name, sub);		// 账户名
			desc = desc.Mid(desc.Find(_T("|"))+1);
			sub = desc.Left(desc.Find(_T("|")));
			sub.Remove(_T('\t'));
			sub = sub.Mid(sub.Find(_T(":"))+1);
			_tcscpy(pep->Account_region, sub);		// 账户域
			desc = desc.Mid(desc.Find(_T("|"))+1);
			sub = desc.Left(desc.Find(_T("|")));
			sub.Remove(_T('\t'));
			sub = sub.Mid(sub.Find(_T(":"))+1);
			_tcscpy(pep->LoginID, sub);				// 登录ID
			desc = desc.Mid(desc.Find(_T("|"))+1);
			desc = desc.Mid(desc.Find(_T("|"))+1);// 跳过"进程信息"
			sub = desc.Left(desc.Find(_T("|")));
			sub.Remove(_T('\t'));
			sub = sub.Mid(sub.Find(_T(":"))+1);
			_tcscpy(pep->ProcessID, sub);			// 进程ID
			desc = desc.Mid(desc.Find(_T("|"))+1);
			sub = desc.Left(desc.Find(_T("|")));
			sub.Remove(_T('\t'));
			sub = sub.Mid(sub.Find(_T(":"))+1);
			_tcscpy(pep->ProcessName, sub);			// 进程名
			desc = desc.Mid(desc.Find(_T("|"))+1);
			desc.Remove(_T('\t'));
			desc = desc.Mid(desc.Find(_T(":"))+1);
			_tcscpy(pep->ExitStatus, desc);			// 进程退出状态

			m_v4689Log.push_back(pep);
		}
	}

	//MyIntBox(m_v4689Log.size());
}

// 按时间排序
bool MySort_time(p_CreateProcess p1, p_CreateProcess p2)
{
	CString s1(p1->date);
	CString s2(p2->date);
	return s1 < s2;
}

// 对创建CMD进程的日志分析
void CLogAnalyze::CtCmdLogAnaly()
{
	if(m_vCMDlog.empty())
		return;

	vector<p_ProcessInfo> v_Creator;
	v4688it it, it4;
	v4689it it1;
	// 拿到 cmd进程 的父进程 相关信息
	for(it = m_vCMDlog.begin(); it != m_vCMDlog.end(); it++)
	{
		p_ProcessInfo pCreator = new _ProcessInfo;
		memset(pCreator, 0, sizeof(_ProcessInfo));
		for(it4 = m_v4688Log.begin(); it4 != m_v4688Log.end(); it4++)
		{
			if(_tcscmp((*it)->creator_processID, (*it4)->New_processID) == 0)
			{
				_tcscpy(pCreator->ProcessName, (*it)->creator_processName);
				_tcscpy(pCreator->ProcessID, (*it)->creator_processID);
				_tcscpy(pCreator->CreateTime, (*it4)->date);
				_tcscpy(pCreator->ParentPrcID, (*it4)->creator_processID);
				_tcscpy(pCreator->ParentPrcName, (*it4)->creator_processName);
			}
		}
		for(it1 = m_v4689Log.begin(); it1 != m_v4689Log.end(); it1++)
		{
			if(_tcscmp((*it)->creator_processID, (*it1)->ProcessID) == 0)
			{
				_tcscpy(pCreator->ExitTime, (*it1)->date);
				_tcscpy(pCreator->ExitStatus, (*it1)->ExitStatus);
			}
		}
		v_Creator.push_back(pCreator);
	}

	vector<p_CreateProcess> v_CreateAll;
	vector<p_ProcessInfo>::iterator it2;
	v4688it it3;
	// 拿到cmd进程的父进程 创建的所有进程
	for(it2 = v_Creator.begin(); it2 != v_Creator.end(); it2++)
	{
		for(it3 = m_v4688Log.begin(); it3 != m_v4688Log.end(); it3++)
		{
			if(_tcscmp((*it2)->ProcessID, (*it3)->creator_processID) == 0 && CString((*it3)->date) >= CString((*it2)->CreateTime) && CString((*it3)->date) <= CString((*it2)->ExitTime))
			{
				v_CreateAll.push_back(*it3);
			}
		}
	}

	// 拿到所有 CMD进程的信息
	vector<p_ProcessInfo> vCmdInfo;
	for(it = m_vCMDlog.begin(); it != m_vCMDlog.end(); it++)
	{
		p_ProcessInfo pCmd = new _ProcessInfo;
		memset(pCmd, 0, sizeof(_ProcessInfo));
			
		_tcscpy(pCmd->ProcessName, (*it)->New_processName);
		_tcscpy(pCmd->ProcessID, (*it)->New_processID);
		_tcscpy(pCmd->ParentPrcName, (*it)->creator_processName);
		_tcscpy(pCmd->ParentPrcID, (*it)->creator_processID);
		_tcscpy(pCmd->CreateTime, (*it)->date);
		
		for(it1 = m_v4689Log.begin(); it1 != m_v4689Log.end(); it1++)
		{
			if(_tcscmp((*it)->New_processID, (*it1)->ProcessID) == 0 && _tcscmp((*it)->New_processName, (*it1)->ProcessName) == 0)
			{
				_tcscpy(pCmd->ExitTime, (*it1)->date);
				_tcscpy(pCmd->ExitStatus, (*it1)->ExitStatus);
			}
		}
		vCmdInfo.push_back(pCmd);
	}

	vector<p_ProcessInfo>::iterator it5;
	v4688it it6;
	vector<p_CreateProcess> vCmdCreate; // CMD进程创建的其他进程的信息
	for(it5 = vCmdInfo.begin(); it5 != vCmdInfo.end(); it5++)
	{
		for(it6 = m_v4688Log.begin(); it6 != m_v4688Log.end(); it6++)
		{
			if(_tcscmp((*it5)->ProcessID, (*it6)->creator_processID) == 0 &&  CString((*it6)->date) >= CString((*it5)->CreateTime) && CString((*it6)->date) <= CString((*it5)->ExitTime))
			{
				vCmdCreate.push_back(*it6);
			}
		}
	}

	// 给容器里的元素排序(按时间从小到大的顺序)
	sort(vCmdCreate.begin(), vCmdCreate.end(), MySort_time);
	sort(v_CreateAll.begin(), v_CreateAll.end(), MySort_time);
	
	//v4688it tit1, tit2;
	//for(tit2 = v_CreateAll.begin(); tit2 != v_CreateAll.end(); tit2++)
	//{
	//	CString str;
	//	str.Format(_T("[%s]在[%s]创建了[%s]"), (*tit2)->creator_processName, (*tit2)->date, (*tit2)->New_processName);
	//	AfxMessageBox(str);
	//	for(tit1 = vCmdCreate.begin(); tit1 != vCmdCreate.end(); tit1++)
	//	{
	//		if(_tcscmp((*tit1)->creator_processID, (*tit2)->New_processID)==0 && _tcscmp((*tit1)->creator_processName, (*tit2)->New_processName)==0)
	//		{
	//			CString str1;
	//			str1.Format(_T("[%s]在[%s]创建了[%s]"), (*tit1)->creator_processName, (*tit1)->date, (*tit1)->New_processName);
	//			AfxMessageBox(str1);
	//		}
	//	}
	//}
	

}

// 获取 0点到4点的所有日志
void CLogAnalyze::Get0_4Log()
{
	if(!m_vSecurity0_4.empty())
		m_vSecurity0_4.clear();

	vector<PSECURITYLOGINFO>::iterator it;
	for(it = m_vSecurityLog.begin(); it != m_vSecurityLog.end(); it++)
	{
		CString date((*it)->date);
		//AfxMessageBox(date);
		CString st = date.Mid(date.Find(_T(' '))+1);
		//AfxMessageBox(st);
		if(st > _T("00:00:00") && st < _T("04:00:00"))
		{
			m_vSecurity0_4.push_back(*it);
		}

		//if(_tcscmp((*it)->event_id, _T("4624")) == 0)
		//{
		//	AfxMessageBox((*it)->describe);
		//}
		//if(_tcscmp((*it)->event_id, _T("4648")) == 0)
		//{
		//	AfxMessageBox((*it)->describe);
		//}
		//if(_tcscmp((*it)->event_id, _T("4672")) == 0)
		//{
		//	AfxMessageBox((*it)->describe);
		//}
	}
}

void Translate4624(PSECURITYLOGINFO pLog, p_UserLogin_4624 p4624)
{
	if(pLog == NULL || p4624 == NULL)
		return;
	memcpy(p4624->event_level, pLog->event_level, sizeof(p4624->event_level));
	memcpy(p4624->date, pLog->date, sizeof(p4624->date));
	memcpy(p4624->source, pLog->source, sizeof(p4624->source));
	memcpy(p4624->event_id, pLog->event_id, sizeof(p4624->event_id));
	memcpy(p4624->task_type, pLog->task_type, sizeof(p4624->task_type));

	CString desc(pLog->describe);
	CString sub = desc.Mid(desc.Find(_T('|'))+1);
	sub = sub.Mid(sub.Find(_T('|'))+1);
	CString dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->uSecurity_ID, dest);				// u 安全ID
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->uAccount_name, dest);			// u 账户名
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->uAccount_region, dest);			// u 账户域
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->uLoginID, dest);					// u 登录ID
	sub = sub.Mid(sub.Find(_T("|"))+1);
	sub = sub.Mid(sub.Find(_T("|"))+1); //跳过"登录信息"
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4624->LoginType, dest);				// 登录类型
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->RestrictedAdmin, dest);			// 受限制的管理员模式
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->VirtualAccount, dest);			// 虚拟账户
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->ElevateToken, dest);				// 提升的令牌
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->ElevateToken, dest);				// 模拟级别
	sub = sub.Mid(sub.Find(_T("|"))+1);
	sub = sub.Mid(sub.Find(_T("|"))+1); //跳过"新登录"
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4624->nSecurity_ID, dest);				// n 安全ID
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->nAccount_name, dest);			// n 账户名称
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->nAccount_region, dest);			// n 账户域 
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->nLoginID, dest);					// n 登录ID 
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->LinkLoginID, dest);				// 链接的登录ID 
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->NetAccount_name, dest);			// 网络账户名称 
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->NetAccount_region, dest);		// 网络账户域 
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->nLogin_GUID, dest);				// 登录GUID 
	sub = sub.Mid(sub.Find(_T("|"))+1);
	sub = sub.Mid(sub.Find(_T("|"))+1); //跳过"进程信息"
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4624->ProcessID, dest);				// 进程ID
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->ProcessName, dest);				// 进程名称 
	sub = sub.Mid(sub.Find(_T("|"))+1);
	sub = sub.Mid(sub.Find(_T("|"))+1); //跳过"网络信息"
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4624->Workstation_name, dest);			// 工作站名称
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->SrcNetAddr, dest);				// 源网络地址 
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->SrcPort, dest);					// 源端口
	sub = sub.Mid(sub.Find(_T("|"))+1);
	sub = sub.Mid(sub.Find(_T("|"))+1); //跳过"详细的身份验证信息"
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4624->LoginProcess, dest);				// 登录进程
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->AuthPackage, dest);				// 身份验证数据包
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->TransmitSev, dest);				// 传递的服务
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->PackageName, dest);				// 数据包名
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4624->SecretKeyLen, dest);				// 秘钥长度

	//AfxMessageBox(sub);
	//AfxMessageBox(dest);
}

void Translate4648(PSECURITYLOGINFO pLog, p_UserLogin_4648 p4648)
{
	if(pLog == NULL || p4648 == NULL)
		return;

	memcpy(p4648->event_level, pLog->event_level, sizeof(p4648->event_level));
	memcpy(p4648->date, pLog->date, sizeof(p4648->date));
	memcpy(p4648->source, pLog->source, sizeof(p4648->source));
	memcpy(p4648->event_id, pLog->event_id, sizeof(p4648->event_id));
	memcpy(p4648->task_type, pLog->task_type, sizeof(p4648->task_type));

	CString desc(pLog->describe);
	CString sub = desc.Mid(desc.Find(_T('|'))+1);
	sub = sub.Mid(sub.Find(_T('|'))+1);
	CString dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4648->uSecurity_ID, dest);				// u 安全ID
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4648->uAccount_name, dest);			// u 账户名
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4648->uAccount_name, dest);			// u 账户域
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4648->uLoginID, dest);					// u 登录ID
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4648->uLoginGUID, dest);				// u 登录GUID
	sub = sub.Mid(sub.Find(_T("|"))+1);
	sub = sub.Mid(sub.Find(_T("|"))+1); //跳过"使用了哪个账户的凭据"
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4648->Account_name, dest);				// 账户名
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4648->Account_region, dest);			// 账户域
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4648->LoginGUID, dest);				// 登录GUID
	sub = sub.Mid(sub.Find(_T("|"))+1);
	sub = sub.Mid(sub.Find(_T("|"))+1); //跳过"目标服务器"
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4648->DestServerName, dest);			// 目标服务器名
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4648->SubjoinInfo, dest);				// 附加信息
	sub = sub.Mid(sub.Find(_T("|"))+1);
	sub = sub.Mid(sub.Find(_T("|"))+1); //跳过"进程信息"
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4648->ProcessID, dest);				// 进程ID
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4648->ProcessName, dest);				// 进程名
	sub = sub.Mid(sub.Find(_T("|"))+1);
	sub = sub.Mid(sub.Find(_T("|"))+1); //跳过"网络信息"
	dest = sub.Left(sub.Find(_T("|")));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(":"))+1);
	_tcscpy(p4648->NetAddr, dest);				// 网络地址
	sub = sub.Mid(sub.Find(_T('|'))+1);
	dest = sub.Left(sub.Find(_T('|')));
	dest.Remove(_T('\t'));
	dest = dest.Mid(dest.Find(_T(':'))+1);
	_tcscpy(p4648->Port, dest);					// 端口

	//AfxMessageBox(sub);
	//AfxMessageBox(dest);
}


void MyVf4624Clear(vector<p_UserLogin_4624>&vt)
{
	if(vt.empty())
		return;
	vector<p_UserLogin_4624>::iterator it;
	for(it = vt.begin(); it!= vt.end(); it++)
	{
		if(*it != NULL)
		{
			delete *it;
			*it = NULL;
		}
	}
	vt.clear();
}

void MyVf4648Clear(vector<p_UserLogin_4648>&vt)
{
	if(vt.empty())
		return;
	vector<p_UserLogin_4648>::iterator it;
	for(it = vt.begin(); it != vt.end(); it++)
	{
		if(*it != NULL)
		{
			delete *it;
			*it = NULL;
		}
	}
	vt.clear();
}

void MyVf4688Clear(vector<p_CreateProcess>&vt)
{
	if(vt.empty())
		return;
	vector<p_CreateProcess>::iterator it;
	for(it = vt.begin(); it != vt.end(); it++)
	{
		if(*it != NULL)
		{
			delete *it;
			*it = NULL;
		}
	}
	vt.clear();
}

// 0-4点的日志分析
void CLogAnalyze::Log0_4Analy()
{
	if(!m_vLogin_4624.empty())
		m_vLogin_4624.clear(); // 这里不能释放空间,只清空容器
		//MySecurityVtClear(m_vLogin);
	if(!m_vfLogin_4624.empty())
		MyVf4624Clear(m_vfLogin_4624);
	if(!m_vfLogin_4648.empty())
		MyVf4648Clear(m_vfLogin_4648);
	if(!m_vCrtPrcs0_4.empty())
		MyVf4688Clear(m_vCrtPrcs0_4);


	// 拿到登录日志
	vector<PSECURITYLOGINFO>::iterator it;
	for(it = m_vSecurity0_4.begin(); it != m_vSecurity0_4.end(); it++)
	{
		if(_tcscmp((*it)->event_id, _T("4624")) == 0)
		{
			m_vLogin_4624.push_back(*it);
		}
		else if(_tcscmp((*it)->event_id, _T("4648")) == 0)
		{
			m_vLogin_4648.push_back(*it);
		}
	}

	vector<PSECURITYLOGINFO>::iterator it1;
	for(it1 = m_vLogin_4624.begin(); it1 != m_vLogin_4624.end(); it1++)
	{
		p_UserLogin_4624 pLgin;
		pLgin = new _UserLogin_4624;
		memset(pLgin, 0, sizeof(_UserLogin_4624));
		Translate4624(*it1, pLgin);
		m_vfLogin_4624.push_back(pLgin);
	}

	vector<PSECURITYLOGINFO>::iterator it2;
	for(it2 = m_vLogin_4648.begin(); it2 != m_vLogin_4648.end(); it2++)
	{
		p_UserLogin_4648 pLogin;
		pLogin = new _UserLogin_4648;
		memset(pLogin, 0, sizeof(_UserLogin_4648));
		Translate4648(*it2, pLogin);
		m_vfLogin_4648.push_back(pLogin);
	}

	vector<p_CreateProcess>::iterator it3;
	for(it3 = m_v4688Log.begin(); it3 != m_v4688Log.end(); it3++)
	{
		CString date((*it3)->date);
		date = date.Mid(date.Find(_T(' '))+1);
		if(date > _T("00:00:00") && date < _T("04:00:00"))
		{
			p_CreateProcess pcp;
			pcp = new _CreateProcess;
			memset(pcp, 0, sizeof(_CreateProcess));
			memcpy(pcp, *it3, sizeof(_CreateProcess));
			m_vCrtPrcs0_4.push_back(pcp);
		}
	}

	//MyIntBox(m_vCrtPrcs0_4.size());
}

CString prefix = NULL;
void MyDesc(CString Desc, vector<pair<CString, CString>>& vt)
{
	CString str = Desc;
	CString dest = str.Left(str.Find(_T('|')));
	dest.Remove(_T('\t'));
	//CString prefix = NULL;
	if(dest.Find(_T(':')) == -1)
		return;
	else
	{
		CString fst;
		CString sec;

		fst = dest.Left(dest.Find(_T(':')));
		sec = dest.Mid(dest.Find(_T(':'))+1);
		if(sec.IsEmpty())
		{
			prefix = fst;
			str = str.Mid(str.Find(_T('|'))+1);
			MyDesc(str, vt);
		}
		else
		{
			fst = prefix + _T("-") + fst;
			pair<CString, CString>pr(fst, sec);

			//CString box;
			//box.Format(_T("[%s]:[%s]"), pr.first, pr.second);
			//AfxMessageBox(box);

			vt.push_back(pr);
			str = str.Mid(str.Find(_T('|'))+1);
			MyDesc(str, vt);
		}
	}
}

void TranslateSecurityLog(PSECURITYLOGINFO pLog, vector<vector<pair<CString, CString>>>&vt)
{
	if(pLog == NULL)
		return;

	vector<pair<CString, CString>> v_log;

	CString str1(pLog->event_level);
	pair<CString, CString> pr1(_T("事件级别"), str1);
	v_log.push_back(pr1);
	CString str2(pLog->date);
	pair<CString, CString> pr2(_T("日期和时间"), str2);
	v_log.push_back(pr2);
	CString str3(pLog->source);
	pair<CString, CString> pr3(_T("来源"), str3);
	v_log.push_back(pr3);
	CString str4(pLog->event_id);
	pair<CString, CString> pr4(_T("事件ID"), str4);
	v_log.push_back(pr4);
	CString str5(pLog->task_type);
	pair<CString, CString> pr5(_T("任务类别"), str5);
	v_log.push_back(pr5);

	CString desc(pLog->describe);
	desc = desc.Mid(desc.Find(_T('|'))+1);
	desc += _T("|");
	MyDesc(desc, v_log);
	vt.push_back(v_log);
}

void CLogAnalyze::Get_IsIP_Log()
{
	vector<PSECURITYLOGINFO>::iterator it;
	for(it = m_vSecurityLog.begin(); it != m_vSecurityLog.end(); it++)
	{
		if(_tcscmp((*it)->event_id, _T("5156")) == 0)
		{
			//AfxMessageBox((*it)->describe);
			TranslateSecurityLog(*it, m_vLog_5156);
		}
		else if(_tcscmp((*it)->event_id, _T("5157")) == 0)
		{
			TranslateSecurityLog(*it, m_vLog_5157);
		}
		else if(_tcscmp((*it)->event_id, _T("5158")) == 0)
		{
			TranslateSecurityLog(*it, m_vLog_5158);
		}
		else if(_tcscmp((*it)->event_id, _T("5152")) == 0)
		{
			TranslateSecurityLog(*it, m_vLog_5152);
		}
		else if(_tcscmp((*it)->event_id, _T("5153")) == 0)
		{
			TranslateSecurityLog(*it, m_vLog_5153);
		}

	}
	//MyIntBox(m_vIsIPLog.size());
}

// 时间格式 2018-07-18 13:25:06 
void CLogAnalyze::GetIPofDate(CString BegDate, CString EndDate)
{
	vector<vector<pair<CString, CString>>>::iterator it;
	for(it = m_vLog_5156.begin(); it != m_vLog_5156.end(); it++)
	{
		vector<pair<CString, CString>>::iterator it1;
		for(it1 = (*it).begin(); it1 != (*it).end(); it1++)
		{
			if((*it1).first == _T("日期和时间"))
			{
				if((*it1).second >= BegDate && (*it1).second <= EndDate)
				{
					p_FiltratedIP IpInfo;
					IpInfo = new _FiltratedIP;
					//memset(IpInfo, 0, sizeof(_FiltratedIP));
					IpInfo->Date = (*it1).second;
					
					for(; it1 != (*it).end(); it1++)
					{
						if((*it1).first == _T("网络信息-方向"))
						{
							if((*it1).second == _T("入站"))
							{
								for(; it1 != (*it).end(); it1++)
								{
									if((*it1).first == _T("网络信息-源地址"))
										IpInfo->IP = (*it1).second;
									else if((*it1).first == _T("网络信息-源端口"))
									{
										IpInfo->Port = (*it1).second;
										break;
									}
								}
							}
							else if((*it1).second == _T("出站"))
							{
								for(; it1 != (*it).end(); it1++)
								{
									if((*it1).first == _T("网络信息-目标地址"))
										IpInfo->IP = (*it1).second;
									else if((*it1).first == _T("网络信息-目标端口"))
									{
										IpInfo->Port = (*it1).second;
										break;
									}
								}
							}
						}
					}
					m_vfIP.push_back(IpInfo);
					break;
				}
			}
		}
	}

	for( it = m_vLog_5157.begin(); it != m_vLog_5157.end(); it++)
	{
		vector<pair<CString, CString>>::iterator it3;
		for(it3 = (*it).begin(); it3 != (*it).end(); it3++)
		{
			if((*it3).first == _T("日期和时间") && (*it3).second >= BegDate && (*it3).second <= EndDate)
			{
				p_FiltratedIP IpInfo3;
				IpInfo3 = new _FiltratedIP;
				IpInfo3->Date = (*it3).second;
				for(; it3 != (*it).end(); it3++)
				{
					if((*it3).first == _T("网络信息-方向"))
					{
						if((*it3).second == _T("入站"))
						{
							for(; it3 != (*it).end(); it3++)
							{
								if((*it3).first == _T("网络信息-源地址"))
									IpInfo3->IP = (*it3).second;
								else if((*it3).first == _T("网络信息-源端口"))
								{
									IpInfo3->Port = (*it3).second;
									break;
								}
							}
						}
						else if((*it3).second == _T("出站"))
						{
							for(; it3 != (*it).end(); it3++)
							{
								if((*it3).first == _T("网络信息-目标地址"))
									IpInfo3->IP = (*it3).second;
								else if((*it3).first == _T("网络信息-目标端口"))
								{
									IpInfo3->Port = (*it3).second;
									break;
								}
							}
						}
					}
				}
				m_vfIP.push_back(IpInfo3);
				break;
			}
		}
	}

	for(it = m_vLog_5158.begin(); it != m_vLog_5158.end(); it++)
	{
		vector<pair<CString, CString>>::iterator it2;
		for(it2 = (*it).begin(); it2 != (*it).end(); it2++)
		{
			if((*it2).first == _T("日期和时间") && (*it2).second >= BegDate && (*it2).second <= EndDate)
			{
				p_FiltratedIP pfIP;
				pfIP = new _FiltratedIP;
				//memset(pfIP, 0, sizeof(_FiltratedIP));
				pfIP->Date = (*it2).second;
				for(; it2 != (*it).end(); it2++)
				{
					if((*it2).first == _T("网络信息-源地址"))
						pfIP->IP = (*it2).second;
					else if((*it2).first == _T("网络信息-源端口"))
					{
						pfIP->Port = (*it2).second;
						break;
					}
				}
				m_vfIP.push_back(pfIP);
				break;
			}
		}
	}

	//MyIntBox(m_vfIP.size());

}

void CLogAnalyze::GetDateOfIP(CString IP)
{
	CString FirstDate = _T("9999-99-99 99:99:99"); 
	CString LastDate = _T("0000-00-00 00:00:00");
	vector<CString>::iterator iit;
	for(iit = m_vIP.begin(); iit != m_vIP.end(); iit++)
	{
		if((*iit) == IP)
			break;
	}
	if(iit == m_vIP.end())
	{
		FirstDate = _T("");
		LastDate = _T("");
		AfxMessageBox(_T("没有此IP的信息"));
		return;
	}

	vector<vector<pair<CString, CString>>>::iterator it;
	for(it = m_vLog_5156.begin(); it != m_vLog_5156.end(); it++)
	{
		CString date;
		vector<pair<CString, CString>>::iterator it1;
		for(it1 = (*it).begin(); it1 != (*it).end(); it1++)  
		{
			if((*it1).first == _T("日期和时间"))
			{
				date = (*it1).second;
			}
			if((*it1).first == _T("网络信息-方向"))
			{
				if((*it1).second == _T("入站"))
				{
					for(;  it1 != (*it).end(); it1++)
					{
						if((*it1).first == _T("网络信息-源地址") && (*it1).second == IP)
						{
							if(date < FirstDate)
							{
								FirstDate = date;
							}
							else if(date > LastDate)
							{
								LastDate = date;
							}
						}
					}
					break;
				}
				else if((*it1).second == _T("出站"))
				{
					for(;  it1 != (*it).end(); it1++)
					{
						if((*it1).first == _T("网络信息-目标地址") && (*it1).second == IP)
						{
							if(date < FirstDate)
							{
								FirstDate = date;
							}
							else if(date > LastDate)
							{
								LastDate = date;
							}
						}
					}
					break;
				}
			}
		}
	}

	for(it = m_vLog_5157.begin(); it != m_vLog_5157.end(); it++)
	{
		CString Date;
		vector<pair<CString, CString>>::iterator it2;
		for(it2 = (*it).begin(); it2 != (*it).end(); it2++)
		{
			if((*it2).first == _T("日期和时间"))
			{
				Date = (*it2).second;
				//AfxMessageBox(Date);
			}
			if((*it2).first == _T("网络信息-方向"))
			{
				if((*it2).second == _T("入站"))
				{
					for(; it2 != (*it).end(); it2++)
					{
						if((*it2).first == _T("网络信息-源地址") && (*it2).second == IP)
						{
							if(Date < FirstDate)
								FirstDate = Date;
							else if(Date > LastDate)
								LastDate = Date;
						}
					}
					break;
				}
				else if((*it2).second == _T("出站"))
				{
					for(; it2 != (*it).end(); it2++)
					{
						if((*it2).first == _T("网络信息-目标地址") && (*it2).second == IP)
						{
							if(Date < FirstDate)
								FirstDate = Date;
							else if(Date > LastDate)
								LastDate = Date;
						}
					}
					break;
				}
			}
		}
	}

	for(it = m_vLog_5152.begin(); it != m_vLog_5152.end(); it++)
	{
		CString Date;
		vector<pair<CString, CString>>::iterator it3;
		for(it3 = (*it).begin(); it3 != (*it).end();it3++)
		{
			if((*it3).first == _T("日期和时间"))
				Date = (*it3).second;
			else if((*it3).first == _T("网络信息-方向"))
			{
				if((*it3).second == _T("入站"))
				{
					for(; it3 != (*it).end(); it3++)
					{
						if((*it3).first == _T("网络信息-源地址") && (*it3).second == IP)
						{
							if(Date < FirstDate)
								FirstDate = Date;
							else if(Date > LastDate)
								LastDate = Date;
						}
					}
					break;
				}
				else if((*it3).second == _T("出站"))
				{
					for(; it3 != (*it).end(); it3++)
					{
						if((*it3).first == _T("网络信息-目标地址") && (*it3).second == IP)
						{
							if(Date < FirstDate)
								FirstDate = Date;
							else if(Date > LastDate)
								LastDate = Date;
						}
					}
					break;
				}
			}
		}
	}

	CString ret;
	ret.Format(_T("[第一次时间:%s, 最后一次时间:%s]"), FirstDate, LastDate);
	AfxMessageBox(ret);

	return;
}

#endif

////////////////上面从容器分析, 下面从数据库分析//////////////////////////////////////////////////////////////

// 通过IP, 获取时间范围
p_Ip_TimeRange CLogAnalyze::GetTimeRange_IP(char *IP)
{
	CString dbName = CTOOLBOX4App::ms_strFullResultPath;
	if(dbName.Right(1) != _T("\\"))
		dbName += _T("\\");
	dbName += _T("主机层\\hongtan004.db");
	TCHAR db[MAX_PATH];
	memset(db, 0, sizeof(db));
	_tcscpy_s(db, dbName);
	char *pDbName = NULL;
	pDbName = UnicodeToUtf8(db);//

	int ret, ret2;
	char ** dbResult = NULL;
	char ** dbResult2 = NULL;
	int nRow, nRow2;
	int nColumn, nColumn2;
	int index, index2;
	int i, i2, j, j2;
	char * errMsg = NULL;
	char * errMsg2 = NULL;
	std::vector<CString> v_Time;	

	ret = sqlite3_open(pDbName, &m_hSql);
	if(ret != SQLITE_OK)
	{
		MessageBox(NULL, _T("打开数据库失败!"), _T("错误"), MB_ICONERROR);
		exit(-1);
	}
	char sql[256];
	memset(sql, 0, sizeof(sql));
	// 通过IP从分表获取 唯一标识
	_snprintf_s(sql, 255, "select screening_platform_links_id from Screening_Platform_Links where direction=\"入站\" and source_address=\"%s\"", IP);
	ret = sqlite3_get_table(m_hSql, sql, &dbResult, &nRow,&nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		//sqlite3_close(m_hSql);
		index = nColumn;
		for(i = 0; i < nRow; i++)
		{
			for(j = 0; j < nColumn; j++)
			{
				char sql[256];
				memset(sql, 0, sizeof(sql));
				// 通过唯一标识, 从主表获取时间
				_snprintf_s(sql, 255, "select record_time ,attack_time from Safe_Log_Handle_Info where safe_log_other_info_id =\"%s\"", dbResult[index]);
				ret2 = sqlite3_get_table(m_hSql, sql, &dbResult2, &nRow2, &nColumn2, &errMsg2);
				if(ret2 == SQLITE_OK)
				{
					index2 = nColumn2;
					for(i2 = 0; i2 < nRow2; i2++)
					{
						for(j2 = 0; j2 < nColumn2; j2++)
						{
							v_Time.push_back(UTF82WCS(dbResult2[index2]));
							index2++;
						}
					}
				}
				index++;
				sqlite3_free_table(dbResult2);
				sqlite3_close(m_hSql);
			}
		}
	}
	sqlite3_free_table(dbResult);
	sqlite3_close(m_hSql);

	// 获取容器中的 最小值 和 最大值 返回对应位置的迭代器
	auto min_time = min_element(v_Time.begin(), v_Time.end());
	auto max_time = max_element(v_Time.begin(), v_Time.end());
	CString minTime = *min_time;
	CString maxtime = *max_time;
	p_Ip_TimeRange pIpTimeRange = new _Ip_TimeRange;
	memset(pIpTimeRange, 0, sizeof(_Ip_TimeRange));
	CString strIP = UTF82WCS(IP);
	_tcscpy_s(pIpTimeRange->IP, strIP);
	_tcscpy_s(pIpTimeRange->FirstTime, minTime);
	_tcscpy_s(pIpTimeRange->LastTime, maxtime);
	pIpTimeRange->IpSource = _T('2');

	if(pDbName != NULL)
	{
		delete pDbName;
		pDbName = NULL;
	}

	return pIpTimeRange;
}

// *通过IP, 获取时间范围
void CLogAnalyze::GetTimeRange_IP(std::vector<CString>&vtIP, vector<p_IpTimeRange_>&vResult)
{
	if(CModule::m_bStop)
		return;
	//CString IP1 = _T("192.168.1.255");	
	//CString IP2 = _T("224.0.0.252");
	//CString IP3 = _T("224.0.0.259");
	//vtIP.push_back(IP1);
	//vtIP.push_back(IP2);
	//vtIP.push_back(IP3);
	std::vector<CString>::iterator it;

	CString dbName = CTOOLBOX4App::ms_strFullResultPath;
	if(dbName.Right(1) != _T("\\"))
		dbName += _T("\\");
	dbName += _T("主机层\\hongtan004.db");
	TCHAR db[MAX_PATH];
	memset(db, 0, sizeof(db));
	_tcscpy_s(db, dbName);
	char *pDbName = NULL;
	pDbName = UnicodeToUtf8(db);//

	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, index;
	char * errMsg = NULL;

	//vector<p_IpTimeRange_> vTimeRange;
	vector<p_IpTimeRange_>::iterator it2;
	for(it = vtIP.begin(); it != vtIP.end(); it++)
	{
		if(CModule::m_bStop)
			return;
		p_IpTimeRange_ pTime = new IpTimeRange_;
		memset(pTime->IP, 0, sizeof(TCHAR)*50);
		memset(pTime->FirstTime, 0, sizeof(TCHAR)*32);
		memset(pTime->LastTime, 0, sizeof(TCHAR)*32);
		memset(&pTime->IpSource, 0, sizeof(TCHAR));
		_tcsncpy_s(pTime->IP, *it, 49);
		vResult.push_back(pTime);
	}


	std::vector<pair<CString,CString>> vtIP1;
	std::vector<pair<CString,CString>>::iterator itr;

	// 打开数据库
	ret = sqlite3_open(pDbName, &m_hSql);
	if(ret != SQLITE_OK)
	{
		if(pDbName != NULL)
		{
			delete []pDbName;
			pDbName = NULL;
		}
		MessageBox(NULL, _T("打开数据库失败!"), _T("错误"), MB_ICONERROR);
		exit(-1);
	}

	if(pDbName != NULL)
	{
		delete []pDbName;
		pDbName = NULL;
	}

	// 多表查询 
	char sql[256];
	for(it2 = vResult.begin(); it2 != vResult.end(); it2++)
	{
		if(CModule::m_bStop)
			return;
		memset(sql, 0, sizeof(sql));
		_snprintf_s(sql, 255, "select record_time from Safe_Log_Handle_Info where safe_log_other_info_id in (select screening_platform_links_id from Screening_Platform_Links where source_address = \"%s\")", UnicodeToUtf8((*it2)->IP));
		ret = sqlite3_get_table(m_hSql, sql, &dbResult, &nRow,&nColumn, &errMsg);
		if(ret == SQLITE_OK)
		{
			index = nColumn;
			for (i = 0; i < nRow; i++)
			{
				if(CModule::m_bStop)
					return;
				(*it2)->vTime.push_back(UTF82WCS(dbResult[index]));
				index++;
			}
			sqlite3_free_table(dbResult);
		}
	}
	sqlite3_close(m_hSql);


	// 从所有时间中 选取最大时间和最小时间
	for(it2 = vResult.begin(); it2 != vResult.end(); it2++)
	{
		if(CModule::m_bStop)
			return;
		if((*it2)->vTime.empty())
		{
			_tcscpy_s((*it2)->FirstTime, _T("9999-99-99 99:99:99"));
			_tcscpy_s((*it2)->LastTime, _T("9999-99-99 99:99:99"));
			(*it2)->IpSource = _T('2');
			continue;
		}
		auto minIt = min_element((*it2)->vTime.begin(), (*it2)->vTime.end());
		auto maxIt = max_element((*it2)->vTime.begin(), (*it2)->vTime.end());

		_tcscpy_s((*it2)->FirstTime, *minIt);
		_tcscpy_s((*it2)->LastTime, *maxIt);

		(*it2)->IpSource = _T('2');
		(*it2)->vTime.clear();
		vector<CString>().swap((*it2)->vTime);
	}

	//MyIntBox(vTimeRange.size());
}
//获取WEB层攻击事件信息
void CLogAnalyze::GetAttackInfo()
{
	CString TempPath = CTOOLBOX4App::ms_strFullResultPath;
	TempPath += _T("主机层\\hongtan004.db");

	char * dbName = NULL;
	dbName = UnicodeToUtf8(TempPath);//

	int ret;
	char ** dbResult = NULL;
	char ** dbResult1 = NULL;
	vector<CString>vtCode;//攻击事件
	vector<CString>vtsinIP;//攻击IP
	std::vector<CString> v_Time;//攻击时间
	char * errMsg = NULL;
	int nRow,nRow1;
	int nColumn,nColumn1;
	int index;
	int i;
	sqlite3 * myDb;
	CString strEventTaskId=CModule::m_csEventTaskId;
	CString strMac=CTOOLBOX4App::ms_strMacAddr;
	ret = sqlite3_open(dbName, &myDb);
	if(ret != SQLITE_OK)
	{
		MessageBox(NULL, _T("打开数据库失败!"), _T("错误"), MB_ICONERROR);
		exit(-1);
	}
	CString strIP;
	CString strIPsql;
	strIPsql.Format(_T("select host_ip from Pc_Account where mac_address='%s'"),strMac);
	char *ipsql;
	ipsql=UnicodeToUtf8(strIPsql);
	ret = sqlite3_get_table(myDb, ipsql, &dbResult, &nRow,&nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{

			strIP = UTF82WCS(dbResult[index]);
		}
	}
	sqlite3_free_table(dbResult);
	char sql[256];
	memset(sql, 0, sizeof(sql));
	strcpy_s(sql, "select distinct attack_code from Web_Attack_Action");
	//strcpy(sql, "select sipcount from watchertrack_attack_record");
	ret = sqlite3_get_table(myDb, sql, &dbResult, &nRow,&nColumn, &errMsg);
	vtCode.clear();
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{

			CString strCode = UTF82WCS(dbResult[index]);
			vtCode.push_back(strCode);
			index++;


		}
	}
	sqlite3_free_table(dbResult);
	

	std::vector<CString>::iterator it,it2;

	sqlite3_exec(myDb,"begin;",0,0,0);
for(it=vtCode.begin();it != vtCode.end(); it++)
{
	//memset(sql, 0, sizeof(sql));
	CString strSql;
	strSql.Format(_T("select distinct attack_ip from Web_Attack_Action where attack_code='%s'"),*it);
	char *sql=UnicodeToUtf8(strSql);
	//strcpy(sql, "select distinct attack_ip from Web_Attack_Action where attack_code='%s'");
	index=0;
	ret = sqlite3_get_table(myDb, sql, &dbResult, &nRow,&nColumn, &errMsg);
	vtsinIP.clear();
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			CString strIP = UTF82WCS(dbResult[index]);
			vtsinIP.push_back(strIP);

			index++;


		}
	}
	sqlite3_free_table(dbResult);
	if(sql!=NULL)
		delete []sql;
	for(it2=vtsinIP.begin();it2 != vtsinIP.end();it2++)
	{
		char *sql;
		CString strsql;		
		CString minTime;
		CString maxtime ;
		strsql.Format(_T("select MAX(attack_time) from Web_Attack_Action where  attack_ip= '%s'and attack_code='%s'"),*it2,*it);
		int index1=0;
		sql=UnicodeToUtf8(strsql);
		ret = sqlite3_get_table(myDb, sql, &dbResult1, &nRow1,&nColumn1, &errMsg);
		if(ret == SQLITE_OK)
		{

			index1 = nColumn1;
			for (i = 0; i < nRow1; i++)
			{

				maxtime = UTF82WCS(dbResult1[index1]);
			}

		}
		sqlite3_free_table(dbResult1);
		if(sql!=NULL)
			delete[] sql;
		strsql.Format(_T("select min(attack_time) from Web_Attack_Action where  attack_ip= '%s'and attack_code='%s'"),*it2,*it);


		sql=UnicodeToUtf8(strsql);
		ret = sqlite3_get_table(myDb, sql, &dbResult1, &nRow1,&nColumn1, &errMsg);
		if(ret == SQLITE_OK)
		{
			index1 = nColumn1;
			for (i = 0; i < nRow1; i++)
			{

				minTime = UTF82WCS(dbResult1[index1]);
			}

		}
		sqlite3_free_table(dbResult1);
		if(sql!=NULL)
			delete[] sql;
		char cSql[256];
		memset(cSql, 0, sizeof(cSql));
		_snprintf_s(cSql, 255, "select count(attack_code) from Web_Attack_Action where attack_ip = \"%s\" and attack_code = \"%s\"",UnicodeToUtf8(*it2), UnicodeToUtf8(*it));
		ret = sqlite3_get_table(myDb, cSql, &dbResult1, &nRow1, &nColumn1, &errMsg);
		index1=0;
		if(ret == SQLITE_OK)
		{
			index1 = nColumn1;
			for (i = 0; i < nRow1; i++)
			{
				//值:dbResult[index];
				int ct = _ttoi(UTF82WCS(dbResult1[index1]));
				CString guid = NewGUID();
				char * cGuid = UnicodeToUtf8(guid);//
				char cSql2[1024];
				memset(cSql2, 0, sizeof(cSql2));
				_snprintf_s(cSql2, 1023, "insert into Attack_Count values('%s', '%s', '%s', '%d', '%s', '%s')", cGuid, UnicodeToUtf8(*it2), UnicodeToUtf8(*it), ct, UnicodeToUtf8(CTOOLBOX4App::ms_strMacAddr), UnicodeToUtf8(CModule::m_csEventTaskId));
				ret = sqlite3_exec(myDb, cSql2, NULL, NULL, &errMsg);
				if(ret != SQLITE_OK)
				{
					MessageBox(NULL, _T("数据库插入数据失败"), _T("错误"), MB_ICONERROR);
				}
				if( errMsg != NULL)
				{
					CString err(UTF82WCS(errMsg));
					sqlite3_free(errMsg);
					MessageBox(NULL, err, _T("数据库错误"), MB_ICONERROR);
					exit(-15);
				}
				delete []cGuid;
				index1++;
			}
			sqlite3_free_table(dbResult1);	// 释放结果
		}
		CString uuid2 = NewGUID();
		CString strInserSql;
		CString strAttackName;
		CString strAttackName1;
		if(*it==_T("sql_injection"))
		{
			strAttackName=_T("01002");
			//strAttackName1=_T("<SQL注入>");
		}
		else if(*it==_T("passwd_attack"))
		{
			strAttackName=_T("01011");

		}
		else if(*it==_T("java_ouin_stream"))
		{
			strAttackName=_T("01006");


			//strAttackName=_T("01006");
		}
		else if(*it==_T("scan_robots"))
		{
			strAttackName=_T("01001");


		}
		else if(*it==_T("file_include"))
		{
			strAttackName=_T("01010");

		}
		else if(*it==_T("xss"))
		{
			strAttackName=_T("01003");

		}
		else if(*it==_T("struts2_remote_command_exe"))
		{
			strAttackName=_T("01004");


		}
		else if(*it==_T("struts2_attack"))
		{
			strAttackName=_T("01015");

		}
		else if(*it==_T("shell_shock"))
		{
			strAttackName=_T("01008");



		}
		else if(*it==_T("http_crlf"))
		{
			strAttackName=_T("01012");

		}
		else if(*it==_T("sensitive_file"))
		{
			strAttackName=_T("01013");

		}
		else if(*it==_T("webshell"))
		{
			strAttackName=_T("01005");


		}
		else if(*it==_T("urljump"))
		{
			strAttackName=_T("01014");

		}
		else if(*it==_T("command_execution"))
		{
			strAttackName=_T("01007");


			//strAttackName=_T("01007");
		}
		//攻击IP分析表
		if(strAttackName==_T("01001")||strAttackName==_T("01002")||strAttackName==_T("01003")||strAttackName==_T("01004")||strAttackName==_T("01005")||strAttackName==_T("01006")||strAttackName==_T("01007")||strAttackName==_T("01008")||strAttackName==_T("01009")&&maxtime.GetLength()>0)
		{

			ATTACKIPANALYSIS attackIPstruct;
			attackIPstruct.host_ip=strIP;
			attackIPstruct.attack_ip=*it2;
			attackIPstruct.attack_begin_time=minTime;
			attackIPstruct.attack_end_time=maxtime;
			attackIPstruct.attack_event_name=strAttackName;
			InsertAttackIpData(attackIPstruct,myDb);
		}
		//事件关联分析表


		EVENT_ASSOCIATION_ANALYSIS eventstruct;
		eventstruct.host_ip=strIP;
		eventstruct.attack_ip=*it2;
		eventstruct.attack_time_begin=minTime;
		eventstruct.attack_time_end=maxtime;
		eventstruct.attack_name=strAttackName;

		Insertevent_association_analysis(eventstruct,myDb);



		//sqlite3_free_table(dbResult);
	}

}
sqlite3_exec(myDb,"commit;",0,0,0);
	sqlite3_close(myDb);
	delete []dbName;
}

// *从数据库中获取攻击IP
void CLogAnalyze::GetAttackIp(vector<CString>&vt)
{
	CString TempPath = CTOOLBOX4App::ms_strFullResultPath;
	TempPath += _T("主机层\\hongtan004.db");

	if(CModule::m_bStop)
		return;

	char * dbName = NULL;
	dbName = UnicodeToUtf8(TempPath);//

	int ret;
	char ** dbResult = NULL;
	int nRow;
	int nColumn;
	int index;
	int i, j;
	char * errMsg = NULL;

	sqlite3 * myDb;
	ret = sqlite3_open(dbName, &myDb);
	if(ret != SQLITE_OK)
	{
		MessageBox(NULL, _T("打开数据库失败!"), _T("错误"), MB_ICONERROR);
		exit(-1);
	}
	//OutputDebugString(_T("C1"));
	char sql[256];
	memset(sql, 0, sizeof(sql));
	strcpy_s(sql, "select distinct attack_ip from Web_Attack_Action");
	//strcpy(sql, "select sipcount from watchertrack_attack_record");
	ret = sqlite3_get_table(myDb, sql, &dbResult, &nRow,&nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				//vSrcIp.push_back(UTF82WCS(dbResult[index]));
				CString sip = UTF82WCS(dbResult[index]);
				if(sip.GetLength() > 7)
					vt.push_back(sip);
		
				index++;
			}
		}
	}
	sqlite3_free_table(dbResult);
	sqlite3_close(myDb);
	delete []dbName;
	//OutputDebugString(_T("C2"));
}
void CLogAnalyze::InsertAttackIpData(ATTACKIPANALYSIS &attackIPstruct,sqlite3 *db)
{
	CString struuid=NewGUID();


	CString strAttackSql;
	strAttackSql.Format(TEXT("insert into  attack_ip_analysis(")
		TEXT("id,")
		TEXT("host_ip,")
		TEXT("attack_ip,")
		TEXT("attack_event_name,")
		TEXT("attack_begin_time,")
		TEXT("attack_end_time,")
		TEXT("mac_address,")
		TEXT("event_task_id")
		TEXT(") values('%s','%s','%s','%s','%s','%s','%s','%s')"),
		struuid,
		attackIPstruct.host_ip,
		attackIPstruct.attack_ip,
		attackIPstruct.attack_event_name,
		attackIPstruct.attack_begin_time,
		attackIPstruct.attack_end_time,
		CTOOLBOX4App::ms_strMacAddr,
		CModule::m_csEventTaskId);
	//strAttackSql.Format(_T("insert into event_association_analysis values('%s', '%s', '', '%s', '%s','', '',' ',' ','%s','%s','','','','','','%s','%s')"),struuid,CTOOLBOX4App::ms_strIP,strAttack_name,suIt->strCreateTime,suIt->strCreateUserName,suIt->strUserName,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
	//2020.11.8
	char *insertsql = UnicodeToUtf8(strAttackSql);
	char * errMsg = NULL;
	int ret = sqlite3_exec(db, insertsql, NULL, NULL, &errMsg);
	if(errMsg != NULL)
	{
		if(insertsql != NULL)
		{
			delete []insertsql;
			insertsql = NULL;
		}

		OutputDebugString(_T("sqlite3_exec1 attack_ip_analysis"));
		sqlite3_free(errMsg);
	}
	if(insertsql != NULL)
	{
		delete []insertsql;
		insertsql = NULL;
	}
}
void CLogAnalyze::Insertevent_association_analysis(EVENT_ASSOCIATION_ANALYSIS &eventstruct,sqlite3 *db)
{
	OutputDebugString(L"641");
	CString struuid=NewGUID();


	CString strAttackSql;
	strAttackSql.Format(TEXT("insert into  event_association_analysis(")
		TEXT("id,")
		TEXT("host_ip,")
		TEXT("attack_ip,")
		TEXT("attack_name,")
		TEXT("attack_time_begin,")
		TEXT("attack_time_end,")
		TEXT("task_name,")
		TEXT("file_md5,")
		TEXT("tool_name,")
		TEXT("login_name,")
		TEXT("suspicious_username,")
		TEXT("operant_hehavior,")
		TEXT("process_id,")
		TEXT("process_name,")
		TEXT("file_name,")
		TEXT("virus_type,")
		TEXT("port_connected_status,")
		TEXT("port,")
		TEXT("mac_address,")
		TEXT("event_task_id")
		TEXT(") values('%s','%s','%s','%s','%s','%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s', '%s','%s','%s','%s')"),
		struuid,
		eventstruct.host_ip,
		eventstruct.attack_ip,
		eventstruct.attack_name,
		eventstruct.attack_time_begin,
		eventstruct.attack_time_end,
		eventstruct.task_name,
		eventstruct.file_md5,
		eventstruct.tool_name,
		eventstruct.login_name,
		eventstruct.suspicious_username,
		eventstruct.operant_hehavior,
		eventstruct.process_id,
		eventstruct.process_name,
		eventstruct.file_name,
		L"",
		eventstruct.port_connected_status,
		eventstruct.port,
		CTOOLBOX4App::ms_strMacAddr,
		CModule::m_csEventTaskId);
	//strAttackSql.Format(_T("insert into event_association_analysis values('%s', '%s', '', '%s', '%s','', '',' ',' ','%s','%s','','','','','','%s','%s')"),struuid,CTOOLBOX4App::ms_strIP,strAttack_name,suIt->strCreateTime,suIt->strCreateUserName,suIt->strUserName,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
	//2020.11.8
	char *insertsql = UnicodeToUtf8(strAttackSql);
	char * errMsg = NULL;
	int ret = sqlite3_exec(db, insertsql, NULL, NULL, &errMsg);
	if(errMsg != NULL)
	{
		if(insertsql != NULL)
		{
			delete []insertsql;
			insertsql = NULL;
		}

		OutputDebugString(_T("sqlite3_exec1 event_association_analysis"));
		sqlite3_free(errMsg);
	}
	if(insertsql != NULL)
	{
		delete []insertsql;
		insertsql = NULL;
	}
}

// *安全日志入库
void LogInsert()
{
	if(CModule::m_bStop)
		return;
	
		//OutputDebugString(_T("B1"));
	//CString FilePath = CTOOLBOX4App::ms_strFullResultPath;
	//FilePath += _T("主机层\\SecurityLogInfoResult.ydxml");
	CString CSQPath = CTOOLBOX4App::ms_strFullResultPath;
	CSQPath += _T("主机层\\hongtan004.db");

	CString eventID = CModule::m_csEventTaskId;
	GetSystemBaseInfo(CSQPath, eventID, CTOOLBOX4App::ms_strMacAddr,CTOOLBOX4App::ms_strIP);
		//GetSystemBaseInfo(FilePath, CSQPath);

	//OutputDebugString(_T("B2"));
}

// *读Web_Attack_Action表获取数据, 写入Attack_Count表
void WebAttackCountInsert()
{
	sqlite3 * m_hSql;
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;
	//CString csDbName = WebResult + _T("\\");
	CString csDbName = CTOOLBOX4App::ms_strFullResultPath;
	csDbName += _T("主机层\\hongtan004.db");
	char * cDbName = UnicodeToUtf8(csDbName);//
	vector<CString> vSrcIp;
	// 打开数据库
	ret = sqlite3_open(cDbName, &m_hSql);
	if(ret != SQLITE_OK)
	{ 
		MessageBox(NULL, _T("打开数据库失败"), _T("错误"), MB_ICONERROR);
		exit(-13);
	}
	sqlite3_exec(m_hSql,"begin;",0,0,0);
	char sql[256];
	memset(sql, 0, sizeof(sql));
	_snprintf_s(sql, 255, "select distinct attack_ip from Web_Attack_Action"); // 准备sql语句
	//_snprintf(sql, 255, "select sipcount from watchertrack_attack_record"); // 准备sql语句
	// 查询数据库
	ret = sqlite3_get_table(m_hSql, sql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				//vSrcIp.push_back(UTF82WCS(dbResult[index]));
				CString sip = UTF82WCS(dbResult[index]);
				if(sip.GetLength() >= 7)
					vSrcIp.push_back(sip);


				index++;
			}
		}
		sqlite3_free_table(dbResult);	// 释放结果
	}
	vector<CString>::iterator it1;
	for(it1 = vSrcIp.begin(); it1 != vSrcIp.end(); ++it1)
	{
		vector<CString> vAttack;
		vector<CString>::iterator it2;
		char cSql[256];
		memset(cSql, 0, sizeof(cSql));
		_snprintf_s(cSql, 255, "select distinct attack_code from Web_Attack_Action where attack_ip = '%s'", UnicodeToUtf8(*it1));
		ret = sqlite3_get_table(m_hSql, cSql, &dbResult, &nRow, &nColumn, &errMsg);
		if(ret == SQLITE_OK)
		{
			index = nColumn;
			for (i = 0; i < nRow; i++)
			{
				for (j = 0; j < nColumn; j++)
				{
					//字段名:dbResult[j], 值:dbResult[index];
					vAttack.push_back(UTF82WCS(dbResult[index]));
					index++;
				}
			}
			if( errMsg != NULL)
			{
				sqlite3_free(errMsg);
			}
			sqlite3_free_table(dbResult);	// 释放结果
		}
		for(it2 = vAttack.begin(); it2 != vAttack.end(); ++it2)
		{
			memset(cSql, 0, sizeof(cSql));
			_snprintf_s(cSql, 255, "select count(attack_code) from Web_Attack_Action where attack_ip = \"%s\" and attack_code = \"%s\"",UnicodeToUtf8(*it1), UnicodeToUtf8(*it2));
			ret = sqlite3_get_table(m_hSql, cSql, &dbResult, &nRow, &nColumn, &errMsg);
			if(ret == SQLITE_OK)
			{
				index = nColumn;
				for (i = 0; i < nRow; i++)
				{
					//值:dbResult[index];
					int ct = _ttoi(UTF82WCS(dbResult[index]));
					CString guid = NewGUID();
					char * cGuid = UnicodeToUtf8(guid);//
					char cSql2[1024];
					memset(cSql2, 0, sizeof(cSql2));
					_snprintf_s(cSql2, 1023, "insert into Attack_Count values('%s', '%s', '%s', '%d', '%s', '%s')", cGuid, UnicodeToUtf8(*it1), UnicodeToUtf8(*it2), ct, UnicodeToUtf8(CTOOLBOX4App::ms_strMacAddr), UnicodeToUtf8(CModule::m_csEventTaskId));
					ret = sqlite3_exec(m_hSql, cSql2, NULL, NULL, &errMsg);
					if(ret != SQLITE_OK)
					{
						MessageBox(NULL, _T("数据库插入数据失败"), _T("错误"), MB_ICONERROR);
					}
					if( errMsg != NULL)
					{
						CString err(UTF82WCS(errMsg));
						sqlite3_free(errMsg);
						MessageBox(NULL, err, _T("数据库错误"), MB_ICONERROR);
						exit(-15);
					}
					delete []cGuid;
					index++;
				}
				sqlite3_free_table(dbResult);	// 释放结果
			}
		}
	}
	if(errMsg != NULL)
		sqlite3_free(errMsg);
	sqlite3_exec(m_hSql,"commit;",0,0,0);
	sqlite3_close(m_hSql);
	delete []cDbName;

}

CString GetSysDisk()
{
	TCHAR sysDir[MAX_PATH] = {0};  
	GetSystemDirectory(sysDir, 128 * sizeof(TCHAR));  
	TCHAR Disk = sysDir[0];  
	CString strDisk(Disk);
	strDisk.MakeUpper();

	return strDisk;
}

// *筛选已入库的安全日志/可疑账户
void CheckSecEx(vector<p_IpTimeRange_>&vtr)
{
	//筛选已入库的安全日志 (详见 NextCheckSec.h)
	//HINSTANCE hHandle = LoadLibrary(_T("NextCheckSecEx.dll"));
	//if(hHandle)
	//{
		CString path = CTOOLBOX4App::ms_strFullResultPath;
		path += _T("主机层\\hongtan004.db");
		//typedef void (*pNextCheckSec)(vector<p_IpTimeRange_>&vt, TCHAR* DBPath);
		//pNextCheckSec mNextCheckSec = (pNextCheckSec)GetProcAddress(hHandle,"NextCheckSec");
		//mNextCheckSec(vtr, path.GetBuffer());
		//OutputDebugString(_T("G1"));
 		NextCheckSec(vtr, path.GetBuffer());
		//OutputDebugString(_T("G2"));
		if(CModule::m_bStop)
			return;

		CString strMac = CTOOLBOX4App::ms_strMacAddr;
		CString strTaskId = CModule::m_csEventTaskId;
		//typedef void (*pAtackBackAn)(TCHAR* dbPath,TCHAR* Mac, TCHAR* EventID);
		//pAtackBackAn mAtackBackAn = (pAtackBackAn)GetProcAddress(hHandle, "AtackBackAn");
		//mAtackBackAn(path.GetBuffer(), strMac.GetBuffer(), strTaskId.GetBuffer());
		
		
		//OutputDebugString(_T("G3"));
		OutputDebugString(TEXT("检查本机可疑账户"));

		//typedef void (*pComparAccounts)(TCHAR* DBPath, TCHAR* Mac, TCHAR* EventID);
		//pComparAccounts mComparAccounts = (pComparAccounts)GetProcAddress(hHandle, "ComparAccounts");
		
		//mComparAccounts(dbPath, Mac, EventID);
		//2021.2.4移到 SuAccount()函数中实现
	//	ComparAccounts(path.GetBuffer(), CTOOLBOX4App::ms_strMacAddr.GetBuffer(), CModule::m_csEventTaskId.GetBuffer());

	//}
	//OutputDebugString(_T("G5"));
}

/*
void SusAccount()
{
	LPUSER_INFO_0 pBuf = NULL;
	DWORD dwLevel = 0;
	DWORD dwPrefMaxLen = MAX_PREFERRED_LENGTH;
	DWORD dwEntriesRead = 0;
	DWORD dwTotalEntries = 0;
	DWORD dwResumeHandle = 0;
	DWORD dwTotalCount = 0;
	NET_API_STATUS nStatus;
	LPTSTR pszServerName = NULL;

	nStatus = NetUserEnum((LPCWSTR)pszServerName,
		dwLevel,
		FILTER_NORMAL_ACCOUNT, // global users
		(LPBYTE*)&pBuf,
		dwPrefMaxLen,
		&dwEntriesRead,
		&dwTotalEntries,
		&dwResumeHandle);
}
*/

// *磁盘可疑文件-轻度
void SuspisiousFile_(int type, vector<p_IpTimeRange_>&vt)
{
	if(CModule::m_bStop)
		return;
	//vector<PSUSPICOUSFILE> vResult;
	CString Path = CTOOLBOX4App::ms_strFullResultPath;
	Path += _T("主机层\\hongtan004.db");
	CString mDisk = NULL;
	if(type == FASTGATHER)
	{
		TCHAR Drive[MAX_PATH] = {0};
		GetSystemDirectory(Drive, MAX_PATH);
		CString fPath(Drive);
		fPath = fPath.Left(1);
		mDisk = fPath;
	}
	else if(type == ALLDISKGATHER)
	{
			//
			//GetLogicalDriveStrings(MAX_PATH,Drive);
		CString Disk = CPage4::m_strDisk;
		Disk.Remove(_T(':'));
		Disk.Remove(_T(';'));
		mDisk = Disk;
	}
	else if(type == CUSTOMGATHER)
	{
		CString Disk = CPage4::m_strSelDisk;
		Disk.Remove(_T(':'));
		Disk.Remove(_T(';'));
		mDisk = Disk;
	}
	CString Mac = CTOOLBOX4App::ms_strMacAddr;
	CString EventTaskId = CModule::m_csEventTaskId;
/*	vt.clear();
	p_IpTimeRange_ p_test;
	p_test = new IpTimeRange_;
	_tcscpy(p_test->IP, _T("10.10.10.10"));
	_tcscpy(p_test->FirstTime, _T("2018-11-22 15:18:07"));
	_tcscpy(p_test->LastTime, _T("2019-06-04 15:48:10"));
	p_test->IpSource = _T('1');
	vt.push_back(p_test);
	p_IpTimeRange_ p_test1;
	p_test1 = new IpTimeRange_;
	_tcscpy(p_test1->IP, _T("10.10.10.11"));
	_tcscpy(p_test1->FirstTime, _T("2018-11-22 15:18:07"));
	_tcscpy(p_test1->LastTime, _T("2019-06-04 15:48:10"));
	p_test1->IpSource = _T('1');
	vt.push_back(p_test1);
	p_IpTimeRange_ p_test2;
	p_test2 = new IpTimeRange_;
	_tcscpy(p_test2->IP, _T("10.10.10.12"));
	_tcscpy(p_test2->FirstTime, _T("2018-11-22 15:18:07"));
	_tcscpy(p_test2->LastTime, _T("2019-06-04 15:48:10"));
	p_test2->IpSource = _T('1');
	vt.push_back(p_test2);*/
	//LightSuspicousFile(Path.GetBuffer(), mDisk.GetBuffer(),/* vt,*/ Mac.GetBuffer(), EventTaskId.GetBuffer());

		// 静态调用
		//LightSuspicousFile(vResult, Path.GetBuffer(), mDisk.GetBuffer(), vt, Mac.GetBuffer(), EventTaskId.GetBuffer());


}
/*
// *磁盘可疑文件 结果入库
void SusFileInsert(vector<PSUSPICOUSFILE>&vt)
{
	sqlite3 * m_hSql;
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;
	// 打开数据库
	CString Path1 = CTOOLBOX4App::ms_strFullResultPath;
	Path1 += _T("主机层\\hongtan004.db");

	char * pDbName = UnicodeToUtf8(Path1);//
	ret = sqlite3_open(pDbName, &m_hSql);
	if(ret != SQLITE_OK)
	{
		MessageBox(NULL, _T("数据库打开失败"), _T("错误"), MB_ICONERROR);
		exit(-19);
	}

	char sql[256] = {0};
	vector<PSUSPICOUSFILE>::iterator it;
	for(it = vt.begin(); it != vt.end(); ++it)
	{
		memset(sql, 0, sizeof(sql));
		CString Guid =  NewGUID();
		sprintf(sql, "insert into Suspicious_File values('%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s',)",
			UnicodeToUtf8(Guid), UnicodeToUtf8((*it)->sourceIpAnalysisId), (*it)->type, UnicodeToUtf8((*it)->attackFileName), UnicodeToUtf8((*it)->fileCreateTime), UnicodeToUtf8((*it)->fileModifyTime), UnicodeToUtf8((*it)->fileInterviewTime), UnicodeToUtf8((*it)->mftUptime), (*it)->fileFlag, UnicodeToUtf8((*it)->ascription), UnicodeToUtf8((*it)->describe), UnicodeToUtf8(CTOOLBOX4App::ms_strMacAddr), UnicodeToUtf8(CModule::m_csEventTaskId)); 
		ret = sqlite3_exec(m_hSql, sql, NULL, NULL, &errMsg);
		if(errMsg != NULL)
		{
			MessageBox(NULL, UTF82WCS(errMsg), _T("错误"), MB_ICONERROR);
			sqlite3_free(errMsg);
			exit(-6);
		}
	}
	sqlite3_close(m_hSql);
	delete []pDbName;
}
*/
CString LogReg = NULL;
CString TimeFormat1 = NULL;
CString TimeFormat2 = NULL;
vector<CString> vTimeColumn;	// 时间格式 字段
// 获取文件夹中符合要求的文件的名字
// sPath: 文件夹路径
// vec1: 存储 符合要求的文件名 的容器
// reg: 筛选文件的正则表达式
BOOL YDGetFilesInDirectory(const CString &sPath,vector<CString> &vec1, CString reg)
{
	CFileFind ff;
	CString szDir = sPath;
	if(szDir.Right(1) != _T("\\"))
	{
		szDir += _T("\\");
	}
	szDir += _T("*.*");
	//szDir += reg;

	/////////////
	char * rg = UnicodeToUtf8(reg);
	std::regex rx(rg);
	std::regex_constants::match_flag_type fl = std::regex_constants::match_default;

	/////////////

	BOOL bFileExit = ff.FindFile(szDir);
	while(bFileExit)
	{
		bFileExit = ff.FindNextFile();
		if( ff.GetFileName() == _T(".") || ff.GetFileName() == _T("..") || ff.IsDirectory())
		{
			continue;
		}
		//CString tempSrcPath = ff.GetFilePath();
		CString strTitle = ff.GetFileName();//得到文件名
		CString tempName = strTitle;
		string strName;
		Wchar_t2String(strName, tempName.GetBuffer());
		if(regex_search(strName, rx, fl))
		{
			vec1.push_back(strTitle);
		}
	}
	ff.Close();

	return TRUE;
}

// 获取中间件 日志文件名正则表达式, 时间格式, 时间字段
// logType: 中间件类型
void GetLogFormat(CString logType)
{
	vTimeColumn.clear();

	LogReg = _T("");
	TimeFormat1 = _T("");
	TimeFormat2 = _T("");

	
	CString FileName = CTOOLBOX4App::ms_ModPath;
	FileName += _T("WebEngine\\watchertrack\\conf\\");
	if(logType == _T("Tomcat"))
		FileName += _T("tomcat.json");
	else if(logType == _T("Apache"))
	{
		FileName += _T("apache.json");
	}
	else if(logType == _T("Nginx"))
	{
		FileName += _T("nginx.json");
	}
	else if(logType == _T("Windows IIS")||logType == _T("IIS"))
	{
		FileName += _T("iis7.json");
	}
	else if(logType == _T("JBOSS"))
	{
		FileName += _T("jboss.json");
	}
	else if(logType == _T("Weblogic"))
	{
		FileName += _T("weblogic.json");
	}
	else if(logType == _T("custom"))
	{
		// 自定义中间件需要使用用户自定义的规则文件
		CString FileName2 =CWebModule::m_strCustomJsonPath;// CTOOLBOX4App::ms_strFullResultPath;

	//	FileName2 += _T("WebAttackAction\\Result1\\MiddleWare.ydjson");
		FileName = FileName2;
	}
	CStdioFile hFile;
	if(!hFile.Open(FileName, CFile::modeRead))
	{
		MessageBox(NULL, _T("打开Json文件失败, 请检查文件是否存在"), _T("错误"), MB_ICONERROR);
		exit(-22);
	}
	CString strRow = NULL;
	CString Reg = NULL;
	hFile.ReadString(strRow);
	while(Reg.IsEmpty() || TimeFormat1.IsEmpty())
	{
		if(strRow.Find(_T("regexNameMark")) != -1)
		{
			//int beg = strRow.Find(_T(':'));
			Reg = strRow.Mid(strRow.Find(_T(':')));
			Reg.Remove(_T(':'));
			Reg.Remove(_T(' '));
			Reg.Remove(_T('\"'));
			Reg.Remove(_T(','));
			LogReg = Reg;
		}
		else if(strRow.Find(_T("logTimeFormat")) != -1)
		{
			CString ch = _T(": \"");
			CString subStr = strRow.Mid(strRow.Find(ch)+ch.GetLength()-1);
			subStr = subStr.Mid(1);
			subStr = subStr.Left(subStr.GetLength()-2);
			TimeFormat1 = subStr;
		}
		hFile.ReadString(strRow);
	}
	hFile.Close();

	CString mTime = TimeFormat1;
	mTime.Remove(_T('['));
	mTime.Remove(_T(']'));
	mTime.Remove(_T('Z'));
	TimeFormat2 = mTime;
	mTime.Replace(_T('-'), _T('/'));
	mTime.Replace(_T(' '), _T('/'));
	mTime.Replace(_T(':'), _T('/'));
	if(mTime.GetAt(0) == _T('/'))
		mTime = mTime.Mid(1);
	int bPos = 0;
	while(!mTime.IsEmpty())
	{
		int ePos = mTime.Find(_T('/'));
		if(ePos != -1)
		{
			CString lstr = mTime.Mid(bPos,ePos);
			vTimeColumn.push_back(lstr);
			mTime = mTime.Mid(ePos+1);
		}
		else
		{
			CString lstr = mTime.Mid(bPos);
			vTimeColumn.push_back(lstr);
			break;
		}
	}

}

CString GetTime(CString Ftime)
{
	CString Year = NULL;
	CString Month = NULL;
	CString Day = NULL;
	CString Hour = NULL;
	CString Minute = NULL;
	CString Second = NULL;
	
	CString retTime = NULL;

	CString tempTime = Ftime;
	CString ttt = _T("25/Aug/2015:11:35:22");
	for(vector<CString>::iterator it = vTimeColumn.begin(); it != vTimeColumn.end(); ++it)
	{
		int bPos = TimeFormat2.Find(*it);
		int ePos = it->GetLength();
		CString sub = tempTime.Mid(bPos,ePos);
		if(it->Find(_T('y')) != -1)	// 年
		{
			Year = sub;
		}
		else if(it->Find(_T('M')) != -1)	// 月
		{
			if(it->GetLength() > 2)
			{
				CString temp = sub.MakeLower();
				if(temp.Find(_T("jan")) != -1)
				{
					Month = _T("01");
				}
				else if(temp.Find(_T("feb")) != -1)
				{
					Month = _T("02");
				}
				else if(temp.Find(_T("mar")) != -1)
				{
					Month = _T("03");
				}
				else if(temp.Find(_T("apr")) != -1)
				{
					Month = _T("04");
				}
				else if(temp.Find(_T("may")) != -1)
				{
					Month = _T("05");
				}
				else if(temp.Find(_T("jun")) != -1)
				{
					Month = _T("06");
				}
				else if(temp.Find(_T("jul")) != -1)
				{
					Month = _T("07");
				}
				else if(temp.Find(_T("aug")) != -1)
				{
					Month = _T("08");
				}
				else if(temp.Find(_T("sep")) != -1)
				{
					Month = _T("09");
				}
				else if(temp.Find(_T("oct")) != -1)
				{
					Month = _T("10");
				}
				else if(temp.Find(_T("nov")) != -1)
				{
					Month = _T("11");
				}
				else if(temp.Find(_T("dec")) != -1)
				{
					Month = _T("12");
				}
			}
			else
			{
				Month = sub;
			}
		}
		else if(it->Find(_T('d')) != -1)	// 日
		{
			Day = sub;
		}
		else if(it->Find(_T('h')) != -1)	// 时 12小时制
		{
			if(it->GetLength() > 1)
			{
				Hour = sub;
			}
			else
			{
				Hour.Format(_T("0%s"), sub);
			}
		}
		else if(it->Find(_T('H')) != -1)	// 时 24 小时制
		{
			if(it->GetLength() > 1)
			{
				Hour = sub;
			}
			else
			{
				Hour.Format(_T("0%s"), sub);
			}
		}
		else if(it->Find(_T('m')) != -1)	// 分
		{
			if(it->GetLength() > 1)
			{
				Minute = sub;
			}
			else
			{
				Minute.Format(_T("0%s"), sub);
			}
		}
		else if(it->Find(_T('s')) != -1)		// 秒
		{
			if(it->GetLength() > 1)
			{
				Second = sub;
			}
			else
			{
				Second.Format(_T("0%s"), sub);
			}
		}	
	}
	if(!Year.IsEmpty() && !Month.IsEmpty() && !Day.IsEmpty() && !Hour.IsEmpty() && !Minute.IsEmpty() && !Second.IsEmpty())
	{
		retTime.Format(_T("%04d-%02d-%02d %02d:%02d:%02d"), _ttoi(Year), _ttoi(Month), _ttoi(Day), _ttoi(Hour), _ttoi(Minute), _ttoi(Second));
	}
	else
	{
		retTime = _T("9999-99-99 99:99:99");
	}

	return retTime;
}

void GetLine(char * buf, vector<p_IpTimeRange_>&vt, CString fIP,DWORDLONG fileSize)
{
	// 时间正则表达式
	//CString TempTime2 = TimeFormat2;

	CString TempTime = TimeFormat2;
	
	int n = TempTime.GetLength();
	for(int i = 0; i < n; ++i)
	{
		int code = (int)TempTime.GetAt(i);
		if(code >= _T('A') && code <= _T('Z'))
		{
			TempTime.SetAt(i, _T('.'));
		}
		else if(code >= _T('a') && code <= _T('z'))
		{
			TempTime.SetAt(i, _T('.'));
		}
	}

	//vector<CString> vTime;
	//CString AnalTime = TimeFormat;
	//GetTime(TempTime, vTime);

	char *pBuffer = buf;
	char Line[102400] = {0};
	memset(Line, 0, sizeof(char)*102400);
	unsigned long long nt = 0;
	int begPos = 0;
	int j = 0;
	regex reg("((1\\d{2}|25[0-5]|2[0-4]\\d|[1-9]?\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)");
	regex timereg(UnicodeToUtf8(TempTime));
	//long t1=GetTickCount();
	//long lt = 0;
//	if(nt<=fileSize)
	{
		while(pBuffer[nt] != NULL)
		{
			if(CModule::m_bStop)
				return;

			if(pBuffer[nt] != '\n')
			{
				//Line[j] = buf[nt];
				++j;
			}
			else
			{
				memcpy(Line, pBuffer+begPos, j+1);
				Line[j] = '\0';
				begPos += j+1;
				j = 0;
				smatch sm;
				string str(Line);
				//long t2=GetTickCount();
#if 0
				// 时间很长, 更换了方法
				for(sregex_iterator it(str.begin(),str.end(),reg),end;it != end;it++)
				{
					CString Ip((*it).str().c_str());
					if(fIP.Find(Ip) != -1)
					{
						for(sregex_iterator it2(str.begin(), str.end(), timereg),end;it2 != end; it2++)
						{
							CString lTime((*it2).str().c_str());
							CString dTime = GetTime(lTime);
							if(dTime.Find(_T("9999")) != -1)
								continue;
							for(vector<p_IpTimeRange_>::iterator it3 = vt.begin(); it3 != vt.end(); ++it3)
							{
								CString attackIp((*it3)->IP);
								if(attackIp == Ip)
								{
									CString firstTime((*it3)->FirstTime);
									CString lastTime((*it3)->LastTime);
									if(firstTime.Find(_T("9999")) != -1)
									{
										_tcscpy((*it3)->FirstTime, dTime);
										_tcscpy((*it3)->LastTime, dTime);
										continue;
									}
									if(firstTime > dTime)
									{
										_tcscpy((*it3)->FirstTime, dTime);
									}
									else if(lastTime < dTime)
									{
										_tcscpy((*it3)->LastTime, dTime);
									}
									continue;
								}
							}

						}
					}
				}
#else
				for(vector<p_IpTimeRange_>::iterator it3 = vt.begin(); it3 != vt.end(); ++it3)
				{
					CString strLine = UTF82WCS(Line);
					if(strLine.Find((*it3)->IP) != -1)
					{
						for(sregex_iterator it2(str.begin(), str.end(), timereg),end;it2 != end; it2++)
						{
							CString lTime((*it2).str().c_str());
							CString dTime = GetTime(lTime);
							if(dTime.Find(_T("9999")) != -1)
								continue;
							CString firstTime((*it3)->FirstTime);
							CString lastTime((*it3)->LastTime);
							if(firstTime.Find(_T("9999")) != -1)
							{
								_tcscpy_s((*it3)->FirstTime, dTime);
								_tcscpy_s((*it3)->LastTime, dTime);
								continue;
							}
							if(firstTime > dTime)
							{
								_tcscpy_s((*it3)->FirstTime, dTime);
							}
							else if(lastTime < dTime)
							{
								_tcscpy_s((*it3)->LastTime, dTime);
							}
							continue;
						}
					}
				}
#endif
				//long t3=GetTickCount();
				//lt += t3-t2;
				memset(Line, 0, sizeof(char)*102400);
			}
			++nt;
			if(nt==fileSize)
			{
				break;
			}
		}

	}

	//long t4=GetTickCount();
	//CString timeInfo;
	//timeInfo.Format(_T("总时间:[%ld], 循环执行时间[%ld]"), t4-t1, lt);
	//AfxMessageBox(timeInfo);
}

CString GetDestTopPath()
{
	TCHAR path[255];
	ZeroMemory(path,255);
	SHGetSpecialFolderPath(0,path,CSIDL_DESKTOPDIRECTORY,0);
	CString dPath(path);

	return dPath;
}

// 从 中间件 所有日志中查找IP的时间范围
void CLogAnalyze::GetTimeFromLog(vector<p_IpTimeRange_>&vtIp)
{
	CString Fip = _T("");
	CString TempPath = CTOOLBOX4App::ms_strFullResultPath;
	TempPath += _T("主机层\\hongtan004.db");

	char * dbName = NULL;
	dbName = UnicodeToUtf8(TempPath);//

	int ret;
	char ** dbResult = NULL;
	char ** dbResult1 = NULL;
	vector<CString>vtCode;//攻击事件
	vector<CString>vtsinIP;//攻击IP
	std::vector<CString> v_Time;//攻击时间
	char * errMsg = NULL;
	int nRow1;
	int nColumn1;
	int i;
	sqlite3 * myDb;
	CString strEventTaskId=CModule::m_csEventTaskId;
	CString strMac=CTOOLBOX4App::ms_strMacAddr;
	ret = sqlite3_open(dbName, &myDb);
	if(ret != SQLITE_OK)
	{
		MessageBox(NULL, _T("打开数据库失败!"), _T("错误"), MB_ICONERROR);
		exit(-1);
	}
	for(vector<p_IpTimeRange_>::iterator itr1 = vtIp.begin(); itr1 != vtIp.end(); ++itr1)
	{
		
		char *sql;
		CString strsql;		
		CString minTime;
		CString maxtime ;
		strsql.Format(_T("select MAX(attack_time) from Web_Attack_Action where  attack_ip= '%s'"),(*itr1)->IP);
		int index1=0;
		sql=UnicodeToUtf8(strsql);
		ret = sqlite3_get_table(myDb, sql, &dbResult1, &nRow1,&nColumn1, &errMsg);
		if(ret == SQLITE_OK)
		{

			index1 = nColumn1;
			for (i = 0; i < nRow1; i++)
			{

				maxtime = UTF82WCS(dbResult1[index1]);
				_tcscpy_s((*itr1)->LastTime, maxtime);
			}

		}
		sqlite3_free_table(dbResult1);
		if(sql!=NULL)
			delete[] sql;
		strsql.Format(_T("select min(attack_time) from Web_Attack_Action where  attack_ip= '%s'"),(*itr1)->IP);


		sql=UnicodeToUtf8(strsql);
		ret = sqlite3_get_table(myDb, sql, &dbResult1, &nRow1,&nColumn1, &errMsg);
		if(ret == SQLITE_OK)
		{
			index1 = nColumn1;
			for (i = 0; i < nRow1; i++)
			{

				minTime = UTF82WCS(dbResult1[index1]);
				_tcscpy_s((*itr1)->FirstTime, minTime);
			}

		}
		sqlite3_free_table(dbResult1);
		if(sql!=NULL)
			delete[] sql;
		//Fip += _T(",");
	}
	sqlite3_close(myDb);
	/*
	CString DeskPath = CTOOLBOX4App::ms_strFullResultPath;
	CParseWebResultFile pase(DeskPath);
	// 测试用
	//CWebModule::m_vLogPath.push_back(pair<CString,CString>(_T("Apache"), _T("D:\\Apache\\logs")));

	WIN32_FIND_DATAW lData;
	vector<pair<CString,CString>>::iterator it1;
	for(it1 = CWebModule::m_vLogPath.begin(); it1 != CWebModule::m_vLogPath.end(); ++it1)
	{
		// 中间件类型
		CString logType  = it1->first;
		CString LogPath = it1->second;
		vector<CString> vFileName;
		
		GetLogFormat(logType);
		// 获取符合条件的文件名
		YDGetFilesInDirectory(LogPath, vFileName, LogReg);
		for(vector<CString>::iterator it = vFileName.begin(); it != vFileName.end(); ++it)
		{
			CString LogName = LogPath + _T("\\") + *it;
			//lpFindFileData
			//LPWIN32_FIND_DATAW lpData;
			memset(&lData, 0, sizeof(WIN32_FIND_DATAW));
			HANDLE hFind = FindFirstFile(LogName, &lData);
			if(lData.nFileSizeHigh == 0 && lData.nFileSizeLow == 0)
			{
				continue;
			}
				DWORDLONG FileSize = (lData.nFileSizeHigh * (MAXDWORD+1)) + lData.nFileSizeLow;
			CString DeskFile = DeskPath + *it;

			CopyFile(LogName, DeskFile, TRUE);

			//////////内存映射
			HANDLE hFile = CreateFile(
				//LogName,					// 文件路径
				DeskFile,
				GENERIC_READ,				// 只读
				FILE_SHARE_READ,			// 只读共享
				nullptr,					// 默认安全属性
				OPEN_EXISTING,				// 只能打开已存在的文件,否则失败
				FILE_FLAG_SEQUENTIAL_SCAN,	// 对文件进行顺序操作而不是随机操作
				nullptr						// 一般为0
				);
			if(hFile == INVALID_HANDLE_VALUE)
			{
				 DWORD errCode =  GetLastError();
				 CString err;
				 err.Format(_T("打开文件失败[%lu][%s]"), errCode, LogName);
				MessageBox(NULL, err, _T("错误"), MB_ICONERROR);
				exit(-23);
			}
			HANDLE hFileMap = CreateFileMapping(
				hFile,				// 文件对象句柄
				nullptr,			// 默认安全属性
				PAGE_READONLY,		// 页面保护,只读
				0,					// 需要的内存大小, 和打开的文件大小一样
				0,					// 
				nullptr				// 共享内存, 不需要,为null
				);
			if(!hFileMap)
			{
				MessageBox(NULL, _T("内存映射失败"), _T("错误"), MB_ICONERROR);
				exit(-24);
			}


			void *pBuffer = MapViewOfFile(
				hFileMap,			// 文件映射句柄
				FILE_MAP_READ,		// 映射文件只读
				0,					// 0 表示从文件开头读取
				0,					
				0					// 0 全部读取
				);
			if(!pBuffer)
			{
				CloseHandle(hFile);
				CloseHandle(hFileMap);
				AfxMessageBox(_T("文件映射失败!"));
				exit(-25);
			}
			CloseHandle(hFile);
			char * cBuffer = (char *)pBuffer;
			vector<CString> vecTmp1;
			//CString strinput=UTF82WCS(cBuffer);
			//CParseWebResultFile parse;
			GetLine(cBuffer, vtIp, Fip,FileSize);
			
			UnmapViewOfFile(pBuffer);
			CloseHandle(hFileMap);
			DeleteFile(DeskFile);
			FindClose(hFind);
		}
	}
	*/
}

// 攻击IP.时间范围入库
void IpTimeInsert(vector<p_IpTimeRange_>&vt)
{
	sqlite3 * m_hSql;
	int ret;
	char ** dbResult = NULL;
	char * errMsg = NULL;
	// 打开数据库
	CString Path1 = CTOOLBOX4App::ms_strFullResultPath;
	Path1 += _T("主机层\\hongtan004.db");

	char * pDbName = UnicodeToUtf8(Path1);//
	ret = sqlite3_open(pDbName, &m_hSql);
	if(ret != SQLITE_OK)
	{
		MessageBox(NULL, _T("数据库打开失败-06"), _T("错误"), MB_ICONERROR);
		exit(-19);
	}

	//char sql[256] = {0};
	vector<p_IpTimeRange_>::iterator it;
	for(it = vt.begin(); it != vt.end(); ++it)
	{
		//memset(sql, 0, sizeof(sql));
		CString Guid =  NewGUID();
		CString sTime((*it)->FirstTime);
		if(sTime.Find(_T("9999")) != -1)
		{
			memset((*it)->FirstTime, 0, sizeof(TCHAR)*32);
			memset((*it)->LastTime, 0, sizeof(TCHAR)*32);
		}
		CString strSql;
		CString strInsertSql;
		strInsertSql.Format(TEXT("insert into Source_Ip_Analysis(")
			TEXT("source_ip_analysis_id,")
			TEXT("ip_address,")
			TEXT("recent_attack_time,")
			TEXT("attack_time_begin,")
			TEXT("attack_time_end,")
			TEXT("ip_library_id,")
			TEXT("ip_section,")
			TEXT("area,")
			TEXT("operator,")
			TEXT("country_phone_num,")
			TEXT("timezone,")
			TEXT("longitude_and_latitude,")
			TEXT("administrative_region_code,")
			TEXT("postcode,")
			TEXT("mac_address,")
			TEXT("ip_source,")
			TEXT("deflag,")
			TEXT("event_task_id) values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')"),
			NewGUID(),
			(*it)->IP,
			_T(""),
			(*it)->FirstTime,
			(*it)->LastTime,
			_T(""),
			_T(""),
			_T(""),
			_T(""),
			_T(""),
			_T(""),
			_T(""),
			_T(""),
			_T(""),
			CTOOLBOX4App::ms_strMacAddr,
			_T("0"),
			_T(""),
			CModule::m_csEventTaskId);
		char * sql=UnicodeToUtf8(strInsertSql);
		//strSql.Format(_T("insert into Source_Ip_Analysis values('%s', '%s', '', '%s', '%s', '', '', '', '', '', '', '', '', '', '%s', '0', '', '%s')",Guid,(*it)->IP,(*it)->FirstTime,(*it)->LastTime,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId));
		//_snprintf(sql, 255, "insert into Source_Ip_Analysis values('%s', '%s', '', '%s', '%s', '', '', '', '', '', '', '', '', '', '%s', '0', '', '%s')", UnicodeToUtf8(Guid), UnicodeToUtf8((*it)->IP), UnicodeToUtf8((*it)->FirstTime), UnicodeToUtf8((*it)->LastTime), UnicodeToUtf8(CTOOLBOX4App::ms_strMacAddr), UnicodeToUtf8(CModule::m_csEventTaskId));
		ret = sqlite3_exec(m_hSql, sql, NULL, NULL, &errMsg);
		if(errMsg != NULL)
		{
			MessageBox(NULL, UTF82WCS(errMsg), _T("错误"), MB_ICONERROR);
			sqlite3_free(errMsg);
			exit(-6);
		}
	}
	sqlite3_close(m_hSql);
	delete []pDbName;
}

// 获取系统所有用户
void GetSystemAccount(vector<CString>&vt)
{
	LPUSER_INFO_0 pBuf = NULL;
	LPUSER_INFO_0 pTmpBuf = NULL;
	DWORD dwLevel = 0;
	DWORD dwPrefMaxLen = MAX_PREFERRED_LENGTH;
	DWORD dwEntriesRead = 0;
	DWORD dwTotalEntries = 0;
	DWORD dwResumeHandle = 0;
	DWORD dwTotalCount = 0;
	NET_API_STATUS nStatus;
	LPTSTR pszServerName = NULL;

	do 
	{
		nStatus = NetUserEnum(
			(LPCWSTR)pszServerName,
			dwLevel,
			FILTER_NORMAL_ACCOUNT, // global users
			(LPBYTE*)&pBuf,
			dwPrefMaxLen,
			&dwEntriesRead,
			&dwTotalEntries,
			&dwResumeHandle);
		if ((nStatus == NERR_Success) || (nStatus == ERROR_MORE_DATA))
		{
			if((pTmpBuf = pBuf) != NULL)
			{
				for(DWORD i = 0 ; i < dwEntriesRead; i++)
				{
					if(pBuf == NULL)
						break;
					CString name;
					name.Format(_T("%s"), pTmpBuf->usri0_name);
					vt.push_back(name);
					//AfxMessageBox(name);
					pTmpBuf++;
					dwTotalCount++;
				}
			}
		}
		else
		{
			//AfxMessageBox(_T("错误"));
		}

		if (pBuf != NULL)
		{
			NetApiBufferFree(pBuf);
			pBuf = NULL;
		}
	}while(nStatus == ERROR_MORE_DATA);
	if (pBuf != NULL)
		NetApiBufferFree(pBuf);

	return;
}
//筛选平台链接分析，主要分析出站方向
void CLogAnalyze::Screening_Platform_Links(sqlite3 *db)
{
	int ret;
	vector<CString> vt_IP;//获取出站IP
	char ** dbResult = NULL;
	char ** dbResult1 = NULL;
	int nRow, nColumn;
	int nRow1, nColumn1;
	int  index1;
	char * errMsg = NULL;
	int index;
	//int index1;
	//int index2;
	char ** dbResult2 = NULL;
	int nRow2, nColumn2;
	int index2;
	char * errMsg2 = NULL;
	vector<CString>::iterator it;
	CString strSql;
//	strSql.Format(_T("SELECT DISTINCT target_address from Screening_Platform_Links where direction='%s'"),_T("出站"));
	//char * getIP=UnicodeToUtf8(strSql);
	const char *getIP ="SELECT DISTINCT target_address from Screening_Platform_Links where direction='departure'";
	 ret =sqlite3_get_table(db, getIP, &dbResult, &nRow, &nColumn, &errMsg);
	
		if(ret == SQLITE_OK)
		{
			index = nColumn;
			for (int i = 0; i < nRow; i++)
			{
				CString strIP =UTF82WCS(dbResult[index]);
				OutputDebugString(strIP);
				//CString strTargetIP=*it;
				CString strSql1;
				CString strMaxTime,strMinTime;
				strSql1.Format(_T("SELECT MAX(create_date) from Screening_Platform_Links where target_address='%s'"),strIP);
				char * ipsql=UnicodeToUtf8(strSql1);
				ret =sqlite3_get_table(db, ipsql, &dbResult1, &nRow1, &nColumn1, &errMsg);
				if(ret == SQLITE_OK)
				{
					index1 = nColumn1;
					for (int j = 0; j < nRow1; j++)
					{
						strMaxTime =UTF82WCS(dbResult1[index1]);
						index1++;
					}
				}
				sqlite3_free_table(dbResult1);
				if(ipsql!=NULL)
				{
					delete[] ipsql;
				}
				strSql.Format(_T("SELECT MIN(create_date) from Screening_Platform_Links where target_address='%s'"),strIP);
				ipsql=UnicodeToUtf8(strSql);
				ret =sqlite3_get_table(db, ipsql, &dbResult2, &nRow2, &nColumn2, &errMsg);
				if(ret == SQLITE_OK)
				{
					index2 = nColumn2;
					for (int k = 0; k < nRow2; k++)
					{
						strMinTime =UTF82WCS(dbResult2[index2]);
						index2++;
					}
				}
				sqlite3_free_table(dbResult2);
				if(ipsql!=NULL)
				{
					delete[] ipsql;
				}
				OutputDebugString(strMaxTime);
				OutputDebugString(strMinTime);
				ATTACKIPANALYSIS attackIPstruct;
				EVENT_ASSOCIATION_ANALYSIS eventstruct;
				attackIPstruct.host_ip=CTOOLBOX4App::ms_strIP;
				attackIPstruct.attack_ip=strIP;
				if(strMinTime==strMaxTime)
				{
					attackIPstruct.attack_begin_time=_T("");
					eventstruct.attack_time_begin=_T("");
				}
				else
				{
					attackIPstruct.attack_begin_time=strMinTime;
					eventstruct.attack_time_begin=strMinTime;
				}
				attackIPstruct.attack_end_time=strMaxTime;
				attackIPstruct.attack_event_name=_T("03012");
				InsertAttackIpData(attackIPstruct,db);


				eventstruct.attack_ip=strIP;
				eventstruct.attack_name=_T("03012");
				eventstruct.host_ip=CTOOLBOX4App::ms_strIP;

				eventstruct.attack_time_end=strMaxTime;
				Insertevent_association_analysis(eventstruct,db);
			//	vt_IP.push_back(strIP);
				index++;
			}
		}
	
	sqlite3_free_table(dbResult);
	if(errMsg!=NULL)
	{
		sqlite3_free(errMsg);
	}
	
	
}
void CLogAnalyze::GetdbTyepByPc_Account(sqlite3 *db,vector<CString> &strDBType)
{
	CString strSql;
	CString cField;
	CString strPrcid;
	CString strTime;
	CString strText;
	CString strLogonName;
	CString strLogonIP;
	CString strDataBaseID;
	int ret;
	char ** dbResult = NULL;

	BOOL IsInsert=FALSE;

	char * errMsg = NULL;

	int nRow;
	int nColumn;
	int index;
	strSql.Format(_T("select database_type from Pc_Account"));
	ret = sqlite3_get_table(db, UnicodeToUtf8(strSql), &dbResult, &nRow,&nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (int i = 0; i < nRow; i++)
		{
			for (int j=0;j<nColumn;j++)
			{
				CString strRS= UTF82WCS(dbResult[index]);
				if (strRS.Find(_T(";"))>=0)
				{
					while (strRS.Find(_T(";"))>=0)
					{

						CString strTemp =strRS.Left(strRS.Find(_T(";")));
						strDBType.push_back(strTemp);
						CString str = strRS.Right(strRS.GetLength()-strTemp.GetLength()-1);
						strRS=str;
						if (strRS.Find(_T(";"))>=0)
						{
							continue;
						}
						else
						{
							strDBType.push_back(strRS);
						}
					}
					
				}
				else
				{
					strDBType.push_back(strRS);
				}


				index++;
			}
		}
		sqlite3_free_table(dbResult);
	}
}
void CLogAnalyze::InsertDatabaseLogonLogbymongoDB(sqlite3 *myDb)
{
	int ret,ret1;
	char ** dbResult = NULL;
	char ** dbResult1 = NULL;
	BOOL IsInsert=FALSE;

	char * errMsg = NULL;
	
	int nRow, nRow1;
	int nColumn, nColumn1;
	int index, index1;
	int  i1, j1;
	

	CString strSql;
	CString cField;
	CString strPrcid;
	CString strTime;
	CString strText;
	CString strLogonName;
	CString strLogonIP;
	CString strDataBaseName;
	CString strIsSucess;
	CString strConn;
	CString strComponent;
	CString strIP,strPort;
	CString strExitTime;
	CString strdtabaseID;
	sqlite3_exec(myDb,"begin;",0,0,0);
	strSql.Format(_T("select mongo_logon_id, mongo_logon_time,mongo_logon_ip,mongo_logon_conn_id,mongo_logon_port,mongo_logon_username,mongo_logon_rs from mongodb_log_logon_infomation where state='logon'"));
	ret = sqlite3_get_table(myDb, UnicodeToUtf8(strSql), &dbResult, &nRow,&nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (int i = 0; i < nRow; i++)
		{
			
			for (int j=0;j<nColumn;j++)
			{

				cField = UTF82WCS(dbResult[j]);
				if(cField==_T("mongo_logon_time"))
				{
					strTime=UTF82WCS(dbResult[index]);
				}
				else if(cField==_T("mongo_logon_id"))
				{
					strdtabaseID=UTF82WCS(dbResult[index]);
				}
				else if(cField==_T("mongo_logon_conn_id"))
				{
					strConn=UTF82WCS(dbResult[index]);
				}
				else if(cField==_T("mongo_logon_ip"))
				{
					strLogonIP=UTF82WCS(dbResult[index]);
				}
				else if(cField==_T("mongo_logon_username"))
				{
					strLogonName=UTF82WCS(dbResult[index]);
				}
				else if(cField==_T("mongo_logon_port"))
				{
					strPort=UTF82WCS(dbResult[index]);
				}
				else if(cField==_T("mongo_logon_rs"))
				{
					strIsSucess=UTF82WCS(dbResult[index]);
					
				}
				
				index++;
			}
			strExitTime=_T("");
			CString GetExitTimeSql;
			GetExitTimeSql.Format(_T("SELECT mongo_logon_time from mongodb_log_logon_infomation where mongo_logon_port='%s' and mongo_logon_conn_id ='%s' and state='exit'"),strPort,strConn);
			ret1 = sqlite3_get_table(myDb, UnicodeToUtf8(GetExitTimeSql), &dbResult1, &nRow1,&nColumn1, &errMsg);
			if(ret1 == SQLITE_OK)
			{
				index1 = nColumn1;
				for ( i1 = 0; i1 < nRow1; i1++)
				{
					for (j1=0;j1<nColumn1;j1++)
					{
						strExitTime=UTF82WCS(dbResult1[index1]);
						if(strExitTime==strTime)
						{
							strExitTime=_T("");
						}
						else if(strIsSucess.GetLength()==0&&strLogonName.GetLength()==0)
						{
							strIsSucess=_T("成功");
						}
						index1++;

					}
				}
				sqlite3_free_table(dbResult1);
			}
			if(strExitTime.GetLength()!=0)
			{
				CString strUpdatesql;
				strUpdatesql.Format(_T("UPDATE mongodb_log_logon_infomation set mongo_logon_rs='成功' where mongo_logon_id='%s'"),strdtabaseID);
				char *sql = UnicodeToUtf8(strUpdatesql);
				char *errMsg = NULL;

				int ret = sqlite3_exec(myDb, sql, NULL, NULL, &errMsg);
				if(errMsg != NULL)
				{

					sqlite3_free(errMsg);
					//exit(-6);
				}
				if(sql)
				{
					delete []sql;
				}
			}
			CString strInsertSql;
			if(strIsSucess.GetLength()!=0)
			{
				strInsertSql.Format(_T("insert into database_logon_log values('%s', '%s','%s', '%s', '%s', '%s','%s','%s','%s','%s','%s')"),NewGUID(),_T("MongoDB"),_T(""),strLogonIP , strLogonName,strConn, strIsSucess,strTime,strExitTime,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
				char *sql = UnicodeToUtf8(strInsertSql);

				char *errMsg = NULL;

				int ret = sqlite3_exec(myDb, sql, NULL, NULL, &errMsg);
				if(errMsg != NULL)
				{

					sqlite3_free(errMsg);
					//exit(-6);
				}
				if(sql)
				{
					delete []sql;
				}

			}
		
		}
		sqlite3_free_table(dbResult);
	}
	sqlite3_exec(myDb,"commit;",0,0,0);
}
void CLogAnalyze::mongoDBLogonLog(sqlite3 *myDb)
{
	int ret,ret3;
	char ** dbResult = NULL;
	char ** dbResult3 = NULL;
	char ** dbResultVersion = NULL;

	char * errMsg = NULL;
	
	int nRow, nRow3,nRow4;
	int nColumn,nColumn3,nColumn4;
	int index,index3,index4;
	int  i3,i4,j3,j4;
	
	CString strSql;
	CString cField;

	CString strTime;
	
	CString strLogonName;
	CString strDataBaseName;
	CString strConn;
	CString strComponent;
	CString strIP,strPort;
	CString strState;
	CString strVersion;
	sqlite3_exec(myDb,"begin;",0,0,0);
	//char *sql= "SELECT sqlserverlog_id,sqlserverlog_time,sqlserverlog_text from sqlserverlog_info where sqlserverlog_source='登录'"; 
	CString strGetVersionSql;
	strGetVersionSql.Format(_T("SELECT database_version from database_info where database_type='MongoDB'"));
	ret = sqlite3_get_table(myDb, UnicodeToUtf8(strGetVersionSql), &dbResultVersion, &nRow4,&nColumn4, &errMsg);
	if(ret == SQLITE_OK)
	{
		index4 = nColumn4;
		for ( i4 = 0; i4 < nRow4; i4++)
		{
			for (j4=0;j4<nColumn4;j4++)
			{
				strVersion=UTF82WCS(dbResultVersion[index4]);
				index4++;
			}
		}
		sqlite3_free_table(dbResultVersion);
	}
	if(strVersion.Find(_T("5"))!=0)
	{
		CString strconn=_T("%conn%");
		strSql.Format(_T("SELECT mongodb_log_component,mongodb_log_context,mongodb_log_time,mongodb_log_msg from mongodb_log_info where mongodb_log_context like '%s'and mongodb_log_component ='NETWORK' OR mongodb_log_component='ACCESS'"),strconn);
		ret = sqlite3_get_table(myDb, UnicodeToUtf8(strSql), &dbResult, &nRow,&nColumn, &errMsg);
		if(ret == SQLITE_OK)
		{
			index = nColumn;
			for (int i = 0; i < nRow; i++)
			{
				for (int j=0;j<nColumn;j++)
				{
					cField = UTF82WCS(dbResult[j]);
					if(cField==_T("mongodb_log_time"))
					{
						strTime=UTF82WCS(dbResult[index]);
					}

					else if(cField==_T("mongodb_log_component"))
					{
						strComponent=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mongodb_log_context"))
					{
						strConn=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mongodb_log_msg"))
					{
						CString strMsg=UTF82WCS(dbResult[index]);

						CString sql ;
						int accessCout;
						sql.Format(_T("SELECT count(*) from mongodb_log_info where mongodb_log_time='%s'and mongodb_log_component='ACCESS'and mongodb_log_context ='%s'"),strTime,strConn);
						ret3 = sqlite3_get_table(myDb, UnicodeToUtf8(sql), &dbResult3, &nRow3,&nColumn3, &errMsg);
						if(ret3 == SQLITE_OK)
						{
							index3 = nColumn3;
							for ( i3 = 0; i3 < nRow3; i3++)
							{
								for (j3=0;j3<nColumn3;j3++)
								{
									accessCout=atoi(dbResult3[index3]);
									index3++;
								}
							}
							sqlite3_free_table(dbResult3);
						}
						if(accessCout==0)
						{
							if(strMsg.Find(_T("from"))>=0&&strComponent.CompareNoCase(_T("NETWORK"))==0)
							{
								CString strTemp=_T("");
								CString Temp;
								Temp= strMsg;
								int index = strMsg.Find(_T("from"));
								CString strIndex;
								strIndex.Format(_T("%d"),index);
								strTemp= Temp.Right(Temp.GetLength()-Temp.Find(_T("from"))-5);

								strIP=strTemp.Left(strTemp.Find(_T(":")));
								Temp=strTemp.Right(strTemp.GetLength()-strIP.GetLength()-1);
								strPort= Temp.Left(Temp.Find(_T(" ")));
								strTemp= Temp.Right(Temp.GetLength()-strPort.GetLength());
								//	strConn=strTemp.Left(strTemp.Find(_T(":"))-1);
								CString strInsertSql;
								strState=_T("logon");
								strInsertSql.Format(_T("insert into mongodb_log_logon_infomation values('%s', '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s')"),NewGUID(),strTime , strIP,strPort, strConn,_T(""),_T(""),_T(""),strState,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
								char *sql = UnicodeToUtf8(strInsertSql);

								char *errMsg = NULL;

								int ret = sqlite3_exec(myDb, sql, NULL, NULL, &errMsg);
								if(errMsg != NULL)
								{

									sqlite3_free(errMsg);
									//exit(-6);
								}
								if(sql)
								{
									delete []sql;
								}
							}
						}

						if(strComponent.CompareNoCase(_T("ACCESS"))==0&&strMsg.Find(_T("from client"))>=0)
						{
							CString strTemp=_T("");
							CString Temp;
							Temp= strMsg;
							CString strLogonRs;
							strTemp=Temp;
							if(strTemp.Find(_T("authentication failed"))>=0)
							{
								strLogonRs=_T("失败");
								strTemp=Temp.Left(Temp.Find(_T(";"))-1);
								Temp=strTemp;
								strPort=Temp.Right(Temp.GetLength()-Temp.ReverseFind(':')-1);
								strTemp=Temp.Left(Temp.ReverseFind(':'));
								Temp=strTemp;
								Temp.TrimLeft();
								Temp.TrimRight();
								strIP=Temp.Right(Temp.GetLength()-Temp.ReverseFind(' '));
								strIP.TrimLeft();
								strIP.TrimRight();
								strTemp=Temp.Left(Temp.ReverseFind(' ')-1);
								Temp=strTemp;
								Temp.TrimLeft();
								Temp.TrimRight();
								CString str = _T("authentication failed for");
								strTemp=Temp.Right(Temp.GetLength()-Temp.Find(_T("authentication failed for"))-str.GetLength());
								Temp=strTemp;
								Temp.TrimLeft();
								Temp.TrimRight();
								strLogonName= Temp.Left(Temp.Find(_T(" ")));
								strTemp=Temp.Right(Temp.GetLength()-strLogonName.GetLength());
								Temp= strTemp;
								Temp.TrimLeft();
								Temp.TrimRight();
								strTemp=Temp.Right(Temp.GetLength()-Temp.Find(_T("on "))-3);
								Temp=strTemp;
								Temp.TrimLeft();
								Temp.TrimRight();
								strDataBaseName=Temp.Left(Temp.Find(_T(" ")));
							}
							if(strTemp.Find(_T("Successfully authenticated"))>=0)
							{
								strLogonRs=_T("成功");
								Temp=strTemp;
								strPort=Temp.Right(Temp.GetLength()-Temp.ReverseFind(':')-1);
								strTemp=Temp.Left(Temp.ReverseFind(':'));
								Temp=strTemp;
								Temp.TrimLeft();
								Temp.TrimRight();
								strIP=Temp.Right(Temp.GetLength()-Temp.ReverseFind(' '));
								strIP.TrimLeft();
								strIP.TrimRight();
								strTemp=Temp.Left(Temp.ReverseFind(' ')-1);
								Temp=strTemp;
								Temp.TrimLeft();
								Temp.TrimRight();
								CString str = _T("Successfully authenticated as principal");
								strTemp=Temp.Right(Temp.GetLength()-Temp.Find(_T("Successfully authenticated as principal"))-str.GetLength());
								Temp=strTemp;
								Temp.TrimLeft();
								Temp.TrimRight();
								strLogonName= Temp.Left(Temp.Find(_T(" ")));
								strTemp=Temp.Right(Temp.GetLength()-strLogonName.GetLength());
								Temp= strTemp;
								Temp.TrimLeft();
								Temp.TrimRight();
								strTemp=Temp.Right(Temp.GetLength()-Temp.Find(_T("on "))-3);
								Temp=strTemp;
								Temp.TrimLeft();
								Temp.TrimRight();
								strDataBaseName=Temp.Left(Temp.Find(_T(" ")));
							}
							CString strInsertSql;
							strState=_T("logon");
							strInsertSql.Format(_T("insert into mongodb_log_logon_infomation values('%s', '%s', '%s','%s', '%s', '%s','%s','%s','%s','%s','%s')"),NewGUID(),strTime , strIP,strPort, strConn,strLogonName,strDataBaseName,strLogonRs,strState,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
							char *sql = UnicodeToUtf8(strInsertSql);

							char *errMsg = NULL;

							int ret = sqlite3_exec(myDb, sql, NULL, NULL, &errMsg);
							if(errMsg != NULL)
							{

								sqlite3_free(errMsg);
								//exit(-6);
							}
							if(sql)
							{
								delete []sql;
							}
						}

					}
					index++;
				}
			}
			sqlite3_free_table(dbResult);
		}
		CString strSqlExit;

		strSqlExit.Format(_T("SELECT mongodb_log_component,mongodb_log_context,mongodb_log_time,mongodb_log_msg from mongodb_log_info where mongodb_log_component ='NETWORK'and mongodb_log_context like '%s'"),strconn);
		ret = sqlite3_get_table(myDb, UnicodeToUtf8(strSqlExit), &dbResult, &nRow,&nColumn, &errMsg);
		if(ret == SQLITE_OK)
		{
			index = nColumn;
			for (int i = 0; i < nRow; i++)
			{
				for (int j=0;j<nColumn;j++)
				{
					cField = UTF82WCS(dbResult[j]);
					if(cField==_T("mongodb_log_time"))
					{
						strTime=UTF82WCS(dbResult[index]);
					}

					else if(cField==_T("mongodb_log_component"))
					{
						strComponent=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mongodb_log_context"))
					{
						strConn=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mongodb_log_msg"))
					{
						CString strMsg=UTF82WCS(dbResult[index]);
						if(strMsg.Find(_T("end"))>=0)
						{

							CString strTemp;
							CString Temp;
							Temp= strMsg;
							strTemp=Temp.Left(Temp.Find(_T("(")));
							strTemp.TrimLeft();
							strTemp.TrimRight();
							Temp=strTemp;
							strPort=Temp.Right(Temp.GetLength()-Temp.Find(_T(":"))-1);
							strTemp=Temp.Left(Temp.Find(_T(":")));
							Temp=strTemp;
							strIP=Temp.Right(Temp.GetLength()-Temp.ReverseFind(' '));
							strIP.TrimLeft();
							strIP.TrimRight();
							CString strInsertSql;
							strState=_T("exit");
							strInsertSql.Format(_T("insert into mongodb_log_logon_infomation values('%s', '%s','%s', '%s', '%s', '%s','%s','%s','%s','%s','%s')"),NewGUID(),strTime , strIP,strPort, strConn,_T(""),_T(""),_T(""),strState,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
							char *sql = UnicodeToUtf8(strInsertSql);

							char *errMsg = NULL;

							int ret = sqlite3_exec(myDb, sql, NULL, NULL, &errMsg);
							if(errMsg != NULL)
							{

								sqlite3_free(errMsg);
								//exit(-6);
							}
							if(sql)
							{
								delete []sql;
							}
						}
					}
					index++;
				}
			}
			sqlite3_free_table(dbResult);
		}
	}
	if(strVersion.Find(_T("5"))==0)
	{
		CString strconn=_T("%conn%");
		CString strSql;
		CString strComponent,strCont,strLogonTime,strMsg,strAttr;
		CString strLogon_IP,strPort,strdatabaseName,strLogon_UserName,strLogon_Rs;
		strSql.Format(_T("SELECT mongodb_log_component,mongodb_log_context,mongodb_log_time,mongodb_log_msg,mongodb_log_attr from mongodb_log_info where mongodb_log_component='ACCESS' and  mongodb_log_context like '%s'"),strconn);
		ret = sqlite3_get_table(myDb, UnicodeToUtf8(strSql), &dbResult, &nRow,&nColumn, &errMsg);
		if(ret == SQLITE_OK)
		{
			index = nColumn;
			for (int i = 0; i < nRow; i++)
			{

				for (int j=0;j<nColumn;j++)
				{

					cField = UTF82WCS(dbResult[j]);
					if(cField==_T("mongodb_log_component"))
					{
						strComponent=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mongodb_log_context"))
					{
						strCont=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mongodb_log_time"))
					{
						strLogonTime=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mongodb_log_msg"))
					{
						strMsg=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mongodb_log_attr"))
					{
						strAttr=UTF82WCS(dbResult[index]);
					}
					index++;

				}
				if(strMsg==_T("Authentication succeeded"))
				{
					strLogon_Rs=_T("成功");
				}
				else if(strMsg==_T("Authentication failed"))
				{
					strLogon_Rs=_T("失败");
				}
				CString stt=_T("principalName:");
				CString strTemp,str;
				strTemp=strAttr;
				str=strTemp.Right(strTemp.GetLength()-strTemp.Find(stt)-stt.GetLength());
				strTemp=str;
				strLogon_UserName=strTemp.Left(strTemp.Find(_T(",")));
				str=strTemp.Right(strTemp.GetLength()-strLogon_UserName.GetLength()-1);
				strTemp=str;
				stt=_T("authenticationDatabase:");
				str=strTemp.Right(strTemp.GetLength()-strTemp.Find(stt)-stt.GetLength());
				strTemp=str;
				strdatabaseName=strTemp.Left(strTemp.Find(_T(",")));
				str=strTemp.Right(strTemp.GetLength()-strdatabaseName.GetLength()-1);
				strTemp=str;
				stt=_T("remote:");
				str=strTemp.Right(strTemp.GetLength()-strTemp.Find(stt)-stt.GetLength());
				strTemp=str;
				strLogon_IP=strTemp.Left(strTemp.Find(_T(":")));
				str=strTemp.Right(strTemp.GetLength()-strLogon_IP.GetLength()-1);
				strTemp=str;
				strPort=strTemp.Left(strTemp.Find(_T(",")));
				CString strInsertSql;
				
				strState=_T("logon");
				if(strMsg==_T("Authentication failed")||strMsg==_T("Authentication succeeded"))
				{
					strInsertSql.Format(_T("insert into mongodb_log_logon_infomation values('%s', '%s', '%s','%s', '%s', '%s','%s','%s','%s','%s','%s')"),NewGUID(),strLogonTime , strLogon_IP,strPort, strCont,strLogon_UserName,strdatabaseName,strLogon_Rs,strState,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
					char *sql = UnicodeToUtf8(strInsertSql);

					char *errMsg = NULL;

					int ret = sqlite3_exec(myDb, sql, NULL, NULL, &errMsg);
					if(errMsg != NULL)
					{

						sqlite3_free(errMsg);
						//exit(-6);
					}
					if(sql)
					{
						delete []sql;
					}
				}
				
			}
			sqlite3_free_table(dbResult);
		}
		strSql=_T("");
		strSql.Format(_T("SELECT mongodb_log_component,mongodb_log_context,mongodb_log_time,mongodb_log_msg,mongodb_log_attr from mongodb_log_info where mongodb_log_msg='Connection ended'"));
		ret = sqlite3_get_table(myDb, UnicodeToUtf8(strSql), &dbResult, &nRow,&nColumn, &errMsg);
		if(ret == SQLITE_OK)
		{
			index = nColumn;
			for (int i = 0; i < nRow; i++)
			{

				for (int j=0;j<nColumn;j++)
				{

					cField = UTF82WCS(dbResult[j]);
					if(cField==_T("mongodb_log_component"))
					{
						strComponent=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mongodb_log_context"))
					{
						strCont=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mongodb_log_time"))
					{
						strLogonTime=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mongodb_log_msg"))
					{
						strMsg=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mongodb_log_attr"))
					{
						strAttr=UTF82WCS(dbResult[index]);
					}
					index++;

				}
				CString strTemp,str;
				strTemp=strAttr;
				CString stt;
				stt=_T("remote:");
				str = strTemp.Right(strTemp.GetLength()-strTemp.Find(stt)-stt.GetLength());
				strTemp=str;
				strLogon_IP=strTemp.Left(strTemp.Find(_T(":")));
				str=strTemp.Right(strTemp.GetLength()-strLogon_IP.GetLength()-1);
				strTemp=str;
				strPort=strTemp.Left(strTemp.Find(_T(",")));
				
				strState=_T("exit");
				CString strInsertSql;
				strInsertSql.Format(_T("insert into mongodb_log_logon_infomation values('%s', '%s','%s', '%s', '%s', '%s','%s','%s','%s','%s','%s')"),NewGUID(),strLogonTime , strLogon_IP,strPort, strCont,_T(""),_T(""),_T(""),strState,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
				char *sql = UnicodeToUtf8(strInsertSql);

				char *errMsg = NULL;

				int ret = sqlite3_exec(myDb, sql, NULL, NULL, &errMsg);
				if(errMsg != NULL)
				{

					sqlite3_free(errMsg);
					//exit(-6);
				}
				if(sql)
				{
					delete []sql;
				}
			}
			sqlite3_free_table(dbResult);
		}
	}
	sqlite3_exec(myDb,"commit;",0,0,0);
}
void CLogAnalyze::InsertDbLog_LogonLog(sqlite3 *db,CString dbType)
{
	
	if(dbType==_T("MySQL"))
	{

	
		CString strSql;
		CString cField;
		CString strPrcid;
		CString strTime;
		CString strText;
		CString strLogonName;
		CString strLogonIP;
		CString strDataBaseID;
		CString strExitTime;
		CString strLogonRs;
		int ret;
		char ** dbResult = NULL;
		char ** dbResult1 = NULL;
		BOOL IsInsert=FALSE;

		char * errMsg = NULL;
	
		int nRow,nRow1;
		int nColumn,nColumn1;
		int index,index1;
		int  i1,j1;
	
		sqlite3_exec(db,"begin;",0,0,0);
		strSql.Format(_T("select * from mysqllog_Info where mysqllog_command='Connect'"));
		ret = sqlite3_get_table(db, UnicodeToUtf8(strSql), &dbResult, &nRow,&nColumn, &errMsg);
		if(ret == SQLITE_OK)
		{
			index = nColumn;
			strLogonRs=_T("");
			strExitTime=_T("");
			for (int i = 0; i < nRow; i++)
			{
				for (int j=0;j<nColumn;j++)
				{
					cField = UTF82WCS(dbResult[j]);
					if(cField==_T("mysqllog_prcid"))
					{
						strPrcid = UTF82WCS(dbResult[index]);

					}
					else if(cField==_T("mysqllog_id"))
					{
						strDataBaseID=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mysqllog_time"))
					{
						strTime = UTF82WCS(dbResult[index]);

					}
					else if(cField==_T("mysqllog_argument"))
					{
					
						strText=UTF82WCS(dbResult[index]);
						if(strText.Find(_T("Access denied for"))<0)
						{
							strLogonName=strText.Left(strText.ReverseFind('@'));
							CString strTemp;
							strTemp=strText.Left(strText.Find(_T(" ")));
							strLogonIP=strTemp.Right(strTemp.GetLength()-strTemp.ReverseFind('@')-1);
							if(strLogonIP.CompareNoCase(_T("localhost"))==0)
							{
								strLogonIP=_T("127.0.0.1");
							}
							IsInsert=FALSE;
						}
						else
						{
							CString strTemp;
							strTemp=strText;
							IsInsert=TRUE;
						}
					

					}
					index++;
				}
				if(!IsInsert)
				{
					strExitTime=_T("");
					CString strGetExitTimeSql;
					strGetExitTimeSql.Format(_T("SELECT mysqllog_time FROM mysqllog_Info where mysqllog_prcid='%s' and mysqllog_command = 'Quit'"),strPrcid);
					ret = sqlite3_get_table(db, UnicodeToUtf8(strGetExitTimeSql), &dbResult1, &nRow1,&nColumn1, &errMsg);
					if(ret == SQLITE_OK)
					{
						index1 = nColumn1;
						for ( i1 = 0; i1 < nRow1; i1++)
						{
							for ( j1=0;j1<nColumn1;j1++)
							{
								strExitTime=UTF82WCS(dbResult1[index1]);
								index1++;
							}
						}
					}
					if(strExitTime!=strTime&&strExitTime.GetLength()!=0)
					{
						strLogonRs=_T("成功");
					}
					else
					{
						strLogonRs=_T("失败");
					}
					CString strInsertSql;
			
					strInsertSql.Format(_T("insert into database_logon_log values('%s', '%s','%s', '%s', '%s', '%s','%s','%s','%s','%s','%s')"),NewGUID(),dbType , strDataBaseID,strLogonIP, strLogonName,strPrcid,strLogonRs,strTime,strExitTime,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
					char *sql = UnicodeToUtf8(strInsertSql);
			
					char *errMsg = NULL;

					int ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
					if(errMsg != NULL)
					{

						sqlite3_free(errMsg);
						//exit(-6);
					}
					if(sql)
					{
						delete []sql;
					}
				}
			
			}
			sqlite3_free_table(dbResult);
		
		}
		sqlite3_exec(db,"commit;",0,0,0);
	}
	else if(dbType==_T("MSSQLSERVER"))
	{
		int ret;
		char ** dbResult = NULL;

		BOOL IsInsert=FALSE;

		char * errMsg = NULL;

		int nRow;
		int nColumn;
		int index;
		CString strSql;
		CString cField;
		CString strPrcid;
		CString strTime;
		CString strText;
		CString strLogonName;
		CString strLogonIP;
		CString strDataBaseID;
		CString strIsSucess;
		sqlite3_exec(db,"begin;",0,0,0);
		//char *sql= "SELECT sqlserverlog_id,sqlserverlog_time,sqlserverlog_text from sqlserverlog_info where sqlserverlog_source='登录'";
		strSql.Format(_T("SELECT sqlserverlog_id,sqlserverlog_time,sqlserverlog_text from sqlserverlog_info where sqlserverlog_source='登录'and sqlserverlog_text like '%s'"),_T("%Login%"));
		ret = sqlite3_get_table(db, UnicodeToUtf8(strSql), &dbResult, &nRow,&nColumn, &errMsg);
		if(ret == SQLITE_OK)
		{
			index = nColumn;
			for (int i = 0; i < nRow; i++)
			{
				for (int j=0;j<nColumn;j++)
				{
					cField = UTF82WCS(dbResult[j]);
					if(cField==_T("sqlserverlog_id"))
					{
						strDataBaseID=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("sqlserverlog_time"))
					{
						strTime=UTF82WCS(dbResult[index]);
						CString strTemp= strTime.Left(strTime.GetLength()-3);
						strTime=strTemp;
					}
					else if(cField==_T("sqlserverlog_text"))
					{
						strText=UTF82WCS(dbResult[index]);
						int len =strText.Find(_T("["));
						CString strRinght=strText.Right(strText.GetLength()-len-1);
						CString strLeft=strRinght.Left(strRinght.ReverseFind(']'));
						CString strTemp = strLeft.Right(strLeft.GetLength()-strLeft.Find(_T(":"))-2);
						strLogonIP=strTemp;
						if(strText.Find(_T("Login failed for user"))>=0)
						{
							strIsSucess=_T("失败");
							strRinght=_T(" ");
							strLeft=_T(" ");
							strLeft=strText.Left(strText.Find(_T(".")));
							strRinght=strLeft.Right(strLeft.GetLength()-strLeft.ReverseFind(' ')-1);
							strLogonName=strRinght;
						}
						else if(strText.Find(_T("Login succeeded for user"))>=0)
						{
							strIsSucess=_T("成功");
							strRinght=_T(" ");
							strLeft=_T(" ");
							strLeft=strText.Left(strText.Find(_T(".")));
							strRinght=strLeft.Right(strLeft.GetLength()-strLeft.ReverseFind(' ')-1);
							strLogonName=strRinght;
						}
					}
					index++;
				}
				CString strInsertSql;

				strInsertSql.Format(_T("insert into database_logon_log values('%s', '%s', '%s','%s', '%s', '%s','%s','%s',' ','%s','%s')"),NewGUID(),dbType , strDataBaseID,strLogonIP, strLogonName,_T(""),strIsSucess,strTime,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
				char *sql = UnicodeToUtf8(strInsertSql);

				char *errMsg = NULL;

				int ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
				if(errMsg != NULL)
				{

					sqlite3_free(errMsg);
					//exit(-6);
				}
				if(sql)
				{
					delete []sql;
				}

			}
			sqlite3_free_table(dbResult);
		}
		sqlite3_exec(db,"commit;",0,0,0);
	}
	else if(dbType==_T("MongoDB"))
	{
		mongoDBLogonLog(db);
		InsertDatabaseLogonLogbymongoDB(db);
	}
}
void CLogAnalyze::GetSuspicious_Log(sqlite3 *db,CString strPrcId,CString strIP,CString strLogonTime,CString strDbType)
{
	if(strDbType==_T("MySQL"))
	{

	
		CString strKeyWord;
		CString logon_name;
		CString csField;
		char ** dbResult = NULL;
		char ** dbResult1 = NULL;
		BOOL IsInsert=FALSE;
		int ret,ret1;
		char * errMsg = NULL;
		char * errMsg1 = NULL;
		char ** dbResult2 = NULL;
		char ** dbResult3 = NULL;
		char ** dbResult4 = NULL;
		char ** dbResult5 = NULL;
		int nRow, nRow1;
		int nColumn, nColumn1;
		int index, index1;
		int i, i1, j, j1;
		for (int k=0;k<KeyWords.size();k++)
		{
			strKeyWord=KeyWords[k];
			CString strSql;
			CString strMysqlLogId;
			CString strText;
			strSql.Format(_T("SELECT mysqllog_id,mysqllog_argument from mysqllog_Info where mysqllog_prcid='%s' and mysqllog_argument like '%s'"),strPrcId,strKeyWord);
			ret = sqlite3_get_table(db,UnicodeToUtf8(strSql),&dbResult,&nRow,&nColumn,&errMsg);
			if(ret==SQLITE_OK)
			{
				index=nColumn;
				for(i=0;i<nRow;i++)
				{
					for ( j=0;j<nColumn;j++)
					{
						csField = UTF82WCS(dbResult[j]);
						if(csField==_T("mysqllog_id"))
						{
							 strMysqlLogId=UTF82WCS(dbResult[index]);
						
						}
						else if(csField==_T("mysqllog_argument"))
						{
							strText=UTF82WCS(dbResult[index]);
						}
						index ++;
					}
					CString strLogonNameSql;
					strLogonNameSql.Format(_T("SELECT logon_name from database_logon_log where prc_id='%s' and database_type='MySQL' and logon_ip ='%s'"),strPrcId,strIP);
					ret1 = sqlite3_get_table(db,UnicodeToUtf8(strLogonNameSql),&dbResult1,&nRow1,&nColumn1,&errMsg1);
					if(ret1==SQLITE_OK)
					{
						index1=nColumn1;
						for(i1=0;i1<nRow1;i1++)
						{
							for ( j1=0;j1<nColumn1;j1++)
							{
								logon_name=UTF82WCS(dbResult1[index1]);
								index1++;
							}
						}
						sqlite3_free_table(dbResult1);
					}
					CString strInsertSql;
				
					CString str = strKeyWord.Mid(1,strKeyWord.GetLength()-2);
					
					strInsertSql.Format(_T("insert into database_suspicious_log values('%s', '%s', '%s', '%s','%s','%s','%s', '%s','%s','%s')"),NewGUID(), strMysqlLogId,strDbType,logon_name,strIP,strLogonTime, str,strText,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
					char *sql = UnicodeToUtf8(strInsertSql);

					char *errMsg = NULL;

					int ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
					if(errMsg != NULL)
					{

						sqlite3_free(errMsg);
						//exit(-6);
					}
					if(sql)
					{
						delete []sql;
					}

				}
				sqlite3_free_table(dbResult);
			}

		}
	}
	if(strDbType==_T("MongoDB"))
	{
		
	}
}
void CLogAnalyze::GetAttackEventByDB(sqlite3 *db,CString strDbType)
{
	if(strDbType==_T("MySQL"))
	{
		int ret5;
		char ** dbResult = NULL;
		char ** dbResult1 = NULL;
		BOOL IsInsert=FALSE;
		CString strKeyWord;
		char * errMsg = NULL;
		char ** dbResult2 = NULL;
		char ** dbResult3 = NULL;
		char ** dbResult4 = NULL;
		char ** dbResult5 = NULL;
		int nRow2,nRow5;
		int nColumn2,nColumn5;
		int index2,index5;
		int i2,i5,j2,j5;
		char * errMsg1 = NULL;
		char * errMsg2 = NULL;
		char * errMsg3 = NULL;
		char * errMsg4 = NULL;
		char * errMsg5 = NULL;
		for (int key=0;key<KeyWords.size();key++)
		{

			
			strKeyWord=KeyWords[key];

			CString strIPByDBlog_blastSql;
			strIPByDBlog_blastSql.Format(_T("SELECT DISTINCT logon_ip from dblog_blast_statistical where db_type='%s'"),strDbType);
			int ret2 = sqlite3_get_table(db,UnicodeToUtf8(strIPByDBlog_blastSql),&dbResult2,&nRow2,&nColumn2,&errMsg);
			if(ret2==SQLITE_OK)
			{
				index2=nColumn2;
				for(i2=0;i2<nRow2;i2++)
				{
					for ( j2=0;j2<nColumn2;j2++)
					{
						CString strLogonIp=UTF82WCS(dbResult2[index2]);
						
						//	if(strIP==strLogonIp)
						{
							ATTACKIPANALYSIS attackIPstruct;
							EVENT_ASSOCIATION_ANALYSIS eventstruct;
							CString strMaxTime,strMinTime,strTime;
							CString strAttackName;
							CString strGetMaxAttackTimeSql,strGetMinAttackTimeSql;
							CString str = strKeyWord.Mid(1,strKeyWord.GetLength()-2);
							strGetMaxAttackTimeSql.Format(_T(" select max(logon_time)  as date from database_suspicious_log where logon_ip='%s' and db_type='%s' and key_word ='%s'"),strLogonIp,strDbType,str);
							ret5 = sqlite3_get_table(db,UnicodeToUtf8(strGetMaxAttackTimeSql),&dbResult5,&nRow5,&nColumn5,&errMsg5);
							if(ret5==SQLITE_OK)
							{
								index5=nColumn5;
								for(i5=0;i5<nRow5;i5++)
								{
									for ( j5=0;j5<nColumn5;j5++)
									{
										strMaxTime=UTF82WCS(dbResult5[index5]);
										attackIPstruct.attack_end_time=strMaxTime;
										eventstruct.attack_time_end=strMaxTime;
										index5++;

									}
								}
								sqlite3_free_table(dbResult5);
							}


							strGetMinAttackTimeSql.Format(_T(" select min(logon_time)  as date from database_suspicious_log  where logon_ip='%s' and db_type='%s'and key_word ='%s'"),strLogonIp,strDbType,str);
							ret5 = sqlite3_get_table(db,UnicodeToUtf8(strGetMinAttackTimeSql),&dbResult5,&nRow5,&nColumn5,&errMsg5);
							if(ret5==SQLITE_OK)
							{
								index5=nColumn5;
								for(i5=0;i5<nRow5;i5++)
								{
									for ( j5=0;j5<nColumn5;j5++)
									{
										strMinTime=UTF82WCS(dbResult5[index5]);
										attackIPstruct.attack_begin_time=strMinTime;
										eventstruct.attack_time_begin=strMinTime;
										index5++;

									}
								}
								sqlite3_free_table(dbResult5);
							}

							if(strKeyWord==_T("%drop table%"))
							{
								strAttackName=_T("05003");
							}
							else if(strKeyWord==_T("%drop function%"))
							{
								strAttackName=_T("05004");
							}
							else if(strKeyWord==_T("%unlock tables%"))
							{
								strAttackName=_T("05005");
							}
							else if(strKeyWord==_T("%load_file()%"))
							{
								strAttackName=_T("05006");
							}
							else if(strKeyWord==_T("%lock tables%"))
							{
								strAttackName=_T("05007");
							}
							else if(strKeyWord==_T("%into dumpfile%"))
							{
								strAttackName=_T("05008");
							}
							else if(strKeyWord==_T("%select * from%"))
							{
								strAttackName=_T("05009");
							}
							else if(strKeyWord==_T("%into outfile%"))
							{
								strAttackName=_T("05010");
							}
							else if(strKeyWord==_T("%show databases%"))
							{
								strAttackName=_T("05011");
							}
							if(eventstruct.attack_time_begin.GetLength()!=0||eventstruct.attack_time_end.GetLength()!=0)
							{
								eventstruct.attack_name=strAttackName;
								attackIPstruct.attack_event_name=strAttackName;
								attackIPstruct.attack_ip=strLogonIp;
								eventstruct.attack_ip=strLogonIp;
								eventstruct.host_ip=CTOOLBOX4App::ms_strIP;
								attackIPstruct.host_ip=CTOOLBOX4App::ms_strIP;
								InsertAttackIpData(attackIPstruct,db);
								Insertevent_association_analysis(eventstruct,db);
							}
						}
						index2++;
					}
				}
				sqlite3_free_table(dbResult2);
			}
		}
	}
}
//获取登录数据库可疑IP
void CLogAnalyze::GetSuspiciousIP(sqlite3 *db, CString strDbType)
{
	if(strDbType==_T("MongoDB"))
	{

		int ret;
		char ** dbResult = NULL;
		char ** dbResult1 = NULL;
		BOOL IsInsert=FALSE;

		char * errMsg = NULL;
		char ** dbResult2 = NULL;
		char ** dbResult3 = NULL;
		char ** dbResult4 = NULL;
		char ** dbResult5 = NULL;
		int nRow, nRow1, nRow2;
		int nColumn, nColumn1,nColumn2;
		int index, index1, index2;
		int i1,i2,j1,j2;
		char * errMsg1 = NULL;
		char * errMsg2 = NULL;
		char * errMsg3 = NULL;
		char * errMsg4 = NULL;
		char * errMsg5 = NULL;



		CString strSql;
		CString cField,cField1;
		CString strPrcid;
		CString strTime;
		CString strLogonName;
		CString strLogonIP;
		CString strDataBaseName;
		CString strIsSucess;
		CString strConn;
		CString strComponent;
		CString strIP,strPort;
		CString strExitTime;
		CString strAttackName;
		sqlite3_exec(db,"begin;",0,0,0);
		CString strGetRsSql;
		strGetRsSql.Format(_T("SELECT mongo_logon_time,mongo_logon_ip,mongo_logon_username, mongo_logon_conn_id from mongodb_log_logon_infomation where mongo_logon_rs='成功'"));
		ret = sqlite3_get_table(db, UnicodeToUtf8(strGetRsSql), &dbResult, &nRow,&nColumn, &errMsg);
		if(ret == SQLITE_OK)
		{
			index = nColumn;
			for (int i = 0; i < nRow; i++)
			{

				for (int j=0;j<nColumn;j++)
				{

					cField = UTF82WCS(dbResult[j]);
					if(cField==_T("mongo_logon_time"))
					{
						strTime=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mongo_logon_ip"))
					{
						strLogonIP=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mongo_logon_username"))
					{
						strLogonName=UTF82WCS(dbResult[index]);
					}
					else if(cField==_T("mongo_logon_conn_id"))
					{
						strConn=UTF82WCS(dbResult[index]);
					}
					index++;

				}
				if(strLogonIP!=_T("127.0.0.1"))
				{
					CString strGetSuspicious_logSql;
					CString strMongodbLogTime;
					CString strKey;
					CString strMongodbText;
					CString strDbType;
					CString strMongoDBLogID;
					strDbType=_T("MongoDB");
					strGetSuspicious_logSql.Format(_T("SELECT mongodb_log_id,mongodb_log_time,mongodb_log_msg from mongodb_log_info where mongodb_log_component='COMMAND' and mongodb_log_context='%s' and mongodb_log_time>'%s'"),strConn,strTime);
					ret = sqlite3_get_table(db, UnicodeToUtf8(strGetSuspicious_logSql), &dbResult1, &nRow1,&nColumn1, &errMsg);
					if(ret == SQLITE_OK)
					{
						index1 = nColumn1;
						for ( i1 = 0; i1 < nRow1; i1++)
						{

							strKey=_T("");
							for (j1=0;j1<nColumn1;j1++)
							{
								cField1= UTF82WCS(dbResult1[j1]);
								if(cField1==_T("mongodb_log_time"))
								{
									strMongodbLogTime=UTF82WCS(dbResult1[index1]);
								}
								else if(cField1==_T("mongodb_log_msg"))
								{
									strMongodbText=UTF82WCS(dbResult1[index1]);
								}
								else if(cField1==_T("mongodb_log_id"))
								{
									strMongoDBLogID=UTF82WCS(dbResult1[index1]);
								}
								index1++;
							}
							if(strMongodbText.Find(_T("drop Database"))>=0||strMongodbText.Find(_T("dropDatabase"))>=0)
							{
								strAttackName=_T("05012");
								strKey=_T("dropDatabase");
							}
							if(strMongodbText.Find(_T("CMD: drop"))>=0)
							{
								strAttackName=_T("05013");
								strKey=_T("drop Collection");
							}
							if(strKey.GetLength()>0)
							{
								CString strInsertSql;
								strInsertSql.Format(_T("insert into database_suspicious_log values('%s', '%s', '%s', '%s','%s','%s','%s', '%s','%s','%s')"),NewGUID(), strMongoDBLogID,strDbType,strLogonName,strLogonIP,strMongodbLogTime, strKey,strMongodbText,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
								char *sql = UnicodeToUtf8(strInsertSql);

								char *errMsg = NULL;

								int ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
								if(errMsg != NULL)
								{

									sqlite3_free(errMsg);
									//exit(-6);
								}
								if(sql)
								{
									delete []sql;
								}
								CString strAttackIP;
								strAttackIP.Format(_T("SELECT logon_firsttime,logon_lasttime, logon_ip from dblog_blast_statistical where success_flag='成功' and db_type='MongoDB'"));
								ret = sqlite3_get_table(db, UnicodeToUtf8(strAttackIP), &dbResult2, &nRow2,&nColumn2, &errMsg);
								CString strFirstTime,strLastTime;
								if(ret == SQLITE_OK)
								{
									index2 = nColumn2;
									for ( i2 = 0; i2 < nRow2; i2++)
									{


										for (j2=0;j2<nColumn2;j2++)
										{
											CString cField2= UTF82WCS(dbResult2[j2]);
											if(cField2==_T("logon_firsttime"))
											{
												strFirstTime=UTF82WCS(dbResult2[index2]);
											}
											else if(cField2==_T("logon_lasttime"))
											{
												strLastTime=UTF82WCS(dbResult2[index2]);
											}
											else if(cField2==_T("logon_ip"))
											{
												CString strLogonIP1=UTF82WCS(dbResult2[index2]);
												//直接在获取可疑日志的函数里添加攻击事件
												if(strLogonIP==strLogonIP1)
												{
													ATTACKIPANALYSIS attackIPstruct;
													EVENT_ASSOCIATION_ANALYSIS eventstruct;
													eventstruct.attack_name=strAttackName;
													attackIPstruct.attack_event_name=strAttackName;
													attackIPstruct.attack_ip=strLogonIP;
													eventstruct.attack_ip=strLogonIP;
													eventstruct.host_ip=CTOOLBOX4App::ms_strIP;
													attackIPstruct.host_ip=CTOOLBOX4App::ms_strIP;
													InsertAttackIpData(attackIPstruct,db);
													Insertevent_association_analysis(eventstruct,db);
												}
											}

											index2++;
										}
									}
									sqlite3_free_table(dbResult2);
								}
							}

						}
						sqlite3_free_table(dbResult1);
					}

				}
			}
			sqlite3_free_table(dbResult);
		}
		sqlite3_exec(db,"commit;",0,0,0);

	
	}
	if(strDbType==_T("MySQL"))
	{

	
		int ret,ret1,ret3,ret4;
		char ** dbResult = NULL;
		char ** dbResult1 = NULL;
		BOOL IsInsert=FALSE;

		char * errMsg = NULL;
		char ** dbResult2 = NULL;
		char ** dbResult3 = NULL;
		char ** dbResult4 = NULL;
		char ** dbResult5 = NULL;
		int nRow, nRow1,nRow3,nRow4;
		int nColumn, nColumn1,nColumn3,nColumn4;
		int index, index1,index3,index4;
		int i, i1,i3,i4, j, j1,j3,j4;
		char * errMsg1 = NULL;
		char * errMsg2 = NULL;
		char * errMsg3 = NULL;
		char * errMsg4 = NULL;
		char * errMsg5 = NULL;
		CString strGetIP;
		CString strIP;
		CString strPrcId;
		strGetIP.Format(_T("SELECT DISTINCT logon_ip from database_logon_log where logon_ip<>'%s'and logon_ip<>'%s' and database_type ='%s'"),CTOOLBOX4App::ms_strIP,_T("127.0.0.1"),strDbType);
		ret=sqlite3_get_table(db,UnicodeToUtf8(strGetIP),&dbResult,&nRow,&nColumn,&errMsg);
		if(ret==SQLITE_OK)
		{
			index=nColumn;
			for(i=0;i<nRow;i++)
			{
				for ( j=0;j<nColumn;j++)
				{
					strIP=UTF82WCS(dbResult[index]);
					CString strGetLogonTime;
					strGetLogonTime.Format(_T("select DISTINCT logon_time from database_logon_log where logon_ip ='%s'and database_type ='%s'"),strIP,strDbType);
				
					ret3=sqlite3_get_table(db,UnicodeToUtf8(strGetLogonTime),&dbResult3,&nRow3,&nColumn3,&errMsg3);
					if(ret3==SQLITE_OK)
					{
						index3=nColumn3;
						for (i3=0;i3<nRow3;i3++)
						{
							for ( j3=0;j3<nColumn3;j3++)
							{
								CString strLogonTime = UTF82WCS(dbResult3[index3]);
								CString strGetCounts;
								strGetCounts.Format(_T("select count(*) from database_logon_log where logon_ip ='%s'and logon_time ='%s'and database_type ='%s'"),strIP,strLogonTime,strDbType);
								ret4=sqlite3_get_table(db,UnicodeToUtf8(strGetCounts),&dbResult4,&nRow4,&nColumn4,&errMsg4);
								if(ret4==SQLITE_OK)
								{
									index4=nColumn4;
									for (i4=0;i4<nRow4;i4++)
									{
										for ( j4=0;j4<nColumn4;j4++)
										{
											int count=0;
											count=atoi(dbResult4[index4]);
											if(count==1)
											{
												CString strGetPrcId;
												strGetPrcId.Format(_T("select DISTINCT prc_id from database_logon_log where logon_ip ='%s'and database_type ='%s'"),strIP,strDbType);
												ret1=sqlite3_get_table(db,UnicodeToUtf8(strGetPrcId),&dbResult1,&nRow1,&nColumn1,&errMsg1);
												if(ret1==SQLITE_OK)
												{
													index1=nColumn1;
													for (i1=0;i1<nRow1;i1++)
													{
														for ( j1=0;j1<nColumn1;j1++)
														{
															strPrcId=UTF82WCS(dbResult1[index1]);
															if(strPrcId==_T("447")&&strIP==_T("192.168.1.37") )
															{
																OutputDebugString(strPrcId);
																OutputDebugString(strIP);
															}
															GetSuspicious_Log(db,strPrcId,strIP,strLogonTime,strDbType);
															
															index1++;
														}
													}
												}
											}
											index4++;
										}
									}
							
								}
								index3++;
							}
						}
					}
				
					index++;
				}
			}
			if(errMsg != NULL)
			{

				sqlite3_free(errMsg);
				//exit(-6);
			}
			sqlite3_free_table(dbResult);
		}
	}
}
//数据库日志用户爆破
void CLogAnalyze::GetDbLogUser_violence_crack(sqlite3 *db,vector<CString>&vtPrcId,CString strDbType)
{
	if(strDbType==_T("MySQL"))
	{

	
		int ret,ret1,ret2,ret3,ret4,ret5;
		char ** dbResult = NULL;
		char ** dbResult1 = NULL;
		BOOL IsInsert=FALSE;

		char * errMsg = NULL;
		char ** dbResult2 = NULL;
		char ** dbResult3 = NULL;
		char ** dbResult4 = NULL;
		char ** dbResult5 = NULL;
		int nRow, nRow1,nRow2,nRow3,nRow4,nRow5;
		int nColumn, nColumn1,nColumn2,nColumn3,nColumn4,nColumn5;
		int index, index1,index2,index3,index4,index5;
		int i1,i2,i3,i4,i5, j1,j2,j3,j4,j5;
		char * errMsg1 = NULL;
		char * errMsg2 = NULL;
		char * errMsg3 = NULL;
		char * errMsg4 = NULL;
		char * errMsg5 = NULL;


		CString strSql;
		CString cField;
		CString strPrcid;
		CString strTime;
		CString strText;
		CString strLogonName;
		CString strLogonIP;
		CString strDataBaseID;
		sqlite3_exec(db,"begin;",0,0,0);
		CString strSelectSql;
		CString strAttackCount;
		CString IsSucces;
		CString strAttackBegin_time;
		CString strAttackEnd_time;
		CString strGetUserNameSql;
		BOOL isAttack=FALSE;
		//CString strLogonName;
		strGetUserNameSql.Format(_T("SELECT DISTINCT logon_name from database_logon_log where database_type ='%s'"),strDbType);
		BOOL bIsSucess;
		ret5=sqlite3_get_table(db,UnicodeToUtf8(strGetUserNameSql),&dbResult5,&nRow5,&nColumn5,&errMsg5);
		if(ret5==SQLITE_OK)
		{
			index5=nColumn5;
			for(i5=0;i5<nRow5;i5++)
			{
				for ( j5=0;j5<nColumn5;j5++)
				{
					strLogonName=UTF82WCS(dbResult5[index5]);
					strSelectSql.Format(_T("SELECT DISTINCT logon_ip from database_logon_log where logon_name='%s'and database_type ='%s'"),strLogonName,strDbType);
					ret = sqlite3_get_table(db, UnicodeToUtf8(strSelectSql), &dbResult, &nRow,&nColumn, &errMsg);
					if(ret==SQLITE_OK)
					{
						CString strTempIP;
						index = nColumn;
						for (int i = 0; i < nRow; i++)
						{
							for (int j=0;j<nColumn;j++)
							{
								strTempIP = UTF82WCS(dbResult[index]);
								if(strTempIP.CompareNoCase(_T("127.0.0.1"))==0)
								{
									index++;
									continue;
								}
								CString strSelectTime;
								strSelectTime.Format(_T("SELECT DISTINCT logon_time from database_logon_log where logon_ip ='%s'and  logon_name='%s'and database_type ='%s'"),strTempIP,strLogonName,strDbType);
								ret1= sqlite3_get_table(db,UnicodeToUtf8(strSelectTime),&dbResult1,&nRow1,&nColumn1,&errMsg1);
								if(ret1==SQLITE_OK)
								{
									index1=nColumn1;
									for(i1=0;i1<nRow1;i1++)
									{
										for ( j1=0;j1<nColumn1;j1++)
										{
											CString strLogon_time;
											strLogon_time=UTF82WCS(dbResult1[index1]);
											CString strAttackCountSql;
											strAttackCountSql.Format(_T("SELECT count (*) from database_logon_log where logon_ip='%s' and logon_time='%s'and  logon_name='%s'and database_type ='%s'"),strTempIP,strLogon_time,strLogonName,strDbType);
											ret2=sqlite3_get_table(db,UnicodeToUtf8(strAttackCountSql),&dbResult2,&nRow2,&nColumn2,&errMsg2);
											if(ret2==SQLITE_OK)
											{
												index2=nColumn2;
												for(i2=0;i2<nRow2;i2++)
												{
													for ( j2=0;j2<nColumn2;j2++)
													{
														int dwAttackCount;
														dwAttackCount= atoi(dbResult2[index2]);
														if(dwAttackCount>=3)
														{
															isAttack=TRUE;
															strAttackCount.Format(_T("%d"),dwAttackCount);
															CString strPrc_idSql;
															strPrc_idSql.Format(_T("SELECT prc_id from database_logon_log where logon_ip='%s' and logon_time='%s'and  logon_name='%s'and database_type ='%s'"),strTempIP,strLogon_time,strLogonName,strDbType);
															ret3=sqlite3_get_table(db,UnicodeToUtf8(strPrc_idSql),&dbResult3,&nRow3,&nColumn3,&errMsg3);
															if(ret3==SQLITE_OK)
															{
																index3=nColumn3;
																for(i3=0;i3<nRow3;i3++)
																{
																	for ( j3=0;j3<nColumn3;j3++)
																	{
																		CString strPrcId;
																		strPrcId=UTF82WCS(dbResult3[index3]);
																		CString strPrcIdCountSql;
																		strPrcIdCountSql.Format(_T("SELECT COUNT(*) from mysqllog_Info where mysqllog_prcid='%s'and mysqllog_time='%s'"),strPrcId,strLogon_time);
																		ret4=sqlite3_get_table(db,UnicodeToUtf8(strPrcIdCountSql),&dbResult4,&nRow4,&nColumn4,&errMsg4);
																		if(ret4==SQLITE_OK)
																		{
																			index4=nColumn4;
																			for(i4=0;i4<nRow4;i4++)
																			{
																				for ( j4=0;j4<nColumn4;j4++)
																				{
																					int prcidcount=atoi(dbResult4[index4]);
																					IsSucces=_T("");
																					if(prcidcount>1)
																					{
																						//IsSucces=_T("失败");
																						continue;
																					}
																					else
																					{
																						//IsSucces=_T("成功");
																						vtPrcId.push_back(strPrcId);
																						bIsSucess=TRUE;
																						break;
																					}
																					index4++;
																				}
																				if(bIsSucess==TRUE)
																				{
																					break;
																				}
																			}
																			sqlite3_free_table(dbResult4);
																		}
																		index3++;
																	}
																	if(bIsSucess==TRUE)
																	{
																		break;
																	}
																}
																sqlite3_free_table(dbResult3);
															}

														}
														index2++;
													}
													if(bIsSucess==TRUE)
													{
														break;
													}
												}
												sqlite3_free_table(dbResult2);
											}
											index1++;
										}

										if(bIsSucess==TRUE)
										{
											break;
										}
									}

									sqlite3_free_table(dbResult1);

								}
								index++;
							}
							if(isAttack)
							{
								isAttack=FALSE;
								char ** dbRs;
								int nR,nC;
								int ind;
								char * Msg;
								CString strGetAttackCout;
								CString strInsertblast_statisticalSql;
								ATTACKIPANALYSIS attackIPstruct;
								EVENT_ASSOCIATION_ANALYSIS eventstruct;
								strGetAttackCout=_T("");
								strGetAttackCout.Format(_T("SELECT count (*) from database_logon_log where logon_ip='%s' and logon_name='%s'and database_type ='%s'"),strTempIP,strLogonName,strDbType);
								int rs=sqlite3_get_table(db,UnicodeToUtf8(strGetAttackCout),&dbRs,&nR,&nC,&Msg);
								if(rs==SQLITE_OK)
								{
									ind=nC;
									for(int ii=0;ii<nR;ii++)
									{
										for ( int jj=0;jj<nC;jj++)
										{
											strAttackCount=UTF82WCS(dbRs[ind]);
											ind++;
										}
									}
									sqlite3_free_table(dbRs);
								}
								CString strMinSql,strMaxSql;
								strMinSql.Format(_T("SELECT MIN(logon_time) from database_logon_log where logon_ip='%s' and logon_name='%s'and database_type ='%s'"),strTempIP,strLogonName,strDbType);
								rs=sqlite3_get_table(db,UnicodeToUtf8(strMinSql),&dbRs,&nR,&nC,&Msg);
								if(rs==SQLITE_OK)
								{
									ind=nC;
									for(int ii=0;ii<nR;ii++)
									{
										for ( int jj=0;jj<nC;jj++)
										{
											strAttackBegin_time=UTF82WCS(dbRs[ind]);
											ind++;
										}
									}
									sqlite3_free_table(dbRs);
								}
								strMaxSql.Format(_T("SELECT MAX(logon_time) from database_logon_log where logon_ip='%s' and logon_name='%s'and database_type ='%s'"),strTempIP,strLogonName,strDbType);
								rs=sqlite3_get_table(db,UnicodeToUtf8(strMaxSql),&dbRs,&nR,&nC,&Msg);
								if(rs==SQLITE_OK)
								{
									ind=nC;
									for(int ii=0;ii<nR;ii++)
									{
										for ( int jj=0;jj<nC;jj++)
										{
											strAttackEnd_time=UTF82WCS(dbRs[ind]);
											ind++;
										}
									}
									sqlite3_free_table(dbRs);
								}
								if(bIsSucess==TRUE)
								{


									attackIPstruct.attack_event_name=_T("05001");
									eventstruct.attack_name=_T("05001");
									IsSucces=_T("成功");
									strInsertblast_statisticalSql.Format(_T("insert into dblog_blast_statistical values('%s', '%s', '%s', '%s', '%s','%s', '%s','%s','%s','%s')"),NewGUID(),strLogonName , strAttackBegin_time,strAttackEnd_time, strAttackCount,IsSucces,strTempIP,strDbType,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);

									bIsSucess=FALSE;
									//break;
								}
								else
								{
									attackIPstruct.attack_event_name=_T("05002");
									eventstruct.attack_name=_T("05002");
									IsSucces=_T("失败");
									strInsertblast_statisticalSql.Format(_T("insert into dblog_blast_statistical values('%s', '%s', '%s', '%s', '%s','%s', '%s','%s','%s','%s')"),NewGUID(),strLogonName , strAttackBegin_time,strAttackEnd_time, strAttackCount,IsSucces,strTempIP,strDbType,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
								}
								char *sql = UnicodeToUtf8(strInsertblast_statisticalSql);

								char *errMsg = NULL;

								int ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
								if(errMsg != NULL)
								{

									sqlite3_free(errMsg);
									//exit(-6);
								}
								if(sql)
								{
									delete []sql;
								}
							
								attackIPstruct.host_ip=CTOOLBOX4App::ms_strIP;
								attackIPstruct.attack_ip=strTempIP;
								if(strAttackBegin_time==strAttackEnd_time)
								{
									attackIPstruct.attack_begin_time=_T("");
									eventstruct.attack_time_begin=_T("");
								}
								else
								{
									attackIPstruct.attack_begin_time=strAttackBegin_time;
									eventstruct.attack_time_begin=strAttackBegin_time;
								}
								attackIPstruct.attack_end_time=strAttackEnd_time;
							
								InsertAttackIpData(attackIPstruct,db);


								eventstruct.attack_ip=strTempIP;
							
								eventstruct.host_ip=CTOOLBOX4App::ms_strIP;

								eventstruct.attack_time_end=strAttackEnd_time;
								Insertevent_association_analysis(eventstruct,db);
							}
						}
						sqlite3_free_table(dbResult);
					}

					index5++;
				} 
			}
			sqlite3_free_table(dbResult5);
		}
		sqlite3_exec(db,"commit;",0,0,0);
	}
	else if(strDbType==_T("MSSQLSERVER"))
	{
		int ret,ret1,ret2,ret3,ret5;
		char ** dbResult = NULL;
		char ** dbResult1 = NULL;
		BOOL IsInsert=FALSE;

		char * errMsg = NULL;
		char ** dbResult2 = NULL;
		char ** dbResult3 = NULL;
		char ** dbResult4 = NULL;
		char ** dbResult5 = NULL;
		int nRow, nRow1,nRow2,nRow3,nRow5;
		int nColumn, nColumn1,nColumn2,nColumn3,nColumn5;
		int index, index1,index2,index3,index5;
		int i1,i2,i3,i5,j1,j2,j3,j5;
		char * errMsg1 = NULL;
		char * errMsg2 = NULL;
		char * errMsg3 = NULL;
		char * errMsg4 = NULL;
		char * errMsg5 = NULL;


		CString strSql;
		CString cField;
		CString strPrcid;
		CString strTime;
		CString strText;
		CString strLogonName;
		CString strLogonIP;
		CString strDataBaseID;
		sqlite3_exec(db,"begin;",0,0,0);
		CString strSelectSql;
		CString strAttackCount;
		CString IsSucces;
		CString strAttackBegin_time;
		CString strAttackEnd_time;
		CString strGetUserNameSql;
		BOOL isAttack=FALSE;
		//CString strLogonName;
		strGetUserNameSql.Format(_T("SELECT DISTINCT logon_name from database_logon_log where database_type ='%s'"),strDbType);
		BOOL bIsSucess;
		ret5=sqlite3_get_table(db,UnicodeToUtf8(strGetUserNameSql),&dbResult5,&nRow5,&nColumn5,&errMsg5);
		if(ret5==SQLITE_OK)
		{
			index5=nColumn5;
			for(i5=0;i5<nRow5;i5++)
			{
				for ( j5=0;j5<nColumn5;j5++)
				{
					strLogonName=UTF82WCS(dbResult5[index5]);
					strSelectSql.Format(_T("SELECT DISTINCT logon_ip from database_logon_log where logon_name='%s'and database_type ='%s'"),strLogonName,strDbType);
					ret = sqlite3_get_table(db, UnicodeToUtf8(strSelectSql), &dbResult, &nRow,&nColumn, &errMsg);
					if(ret==SQLITE_OK)
					{
						CString strTempIP;
						index = nColumn;
						for (int i = 0; i < nRow; i++)
						{
							for (int j=0;j<nColumn;j++)
							{
								strTempIP = UTF82WCS(dbResult[index]);
								if(strTempIP.CompareNoCase(_T("127.0.0.1"))==0)
								{
									index++;
									continue;
								}
								CString strSelectTime;
								strSelectTime.Format(_T("SELECT DISTINCT logon_time from database_logon_log where logon_ip ='%s'and  logon_name='%s'and database_type ='%s'"),strTempIP,strLogonName,strDbType);
								ret1= sqlite3_get_table(db,UnicodeToUtf8(strSelectTime),&dbResult1,&nRow1,&nColumn1,&errMsg1);
								if(ret1==SQLITE_OK)
								{
									index1=nColumn1;
									for(i1=0;i1<nRow1;i1++)
									{
										for ( j1=0;j1<nColumn1;j1++)
										{
											CString strLogon_time;
											strLogon_time=UTF82WCS(dbResult1[index1]);
											CString strAttackCountSql;
											strAttackCountSql.Format(_T("SELECT count (*) from database_logon_log where logon_ip='%s' and logon_time='%s'and  logon_name='%s'and database_type ='%s'"),strTempIP,strLogon_time,strLogonName,strDbType);
											ret2=sqlite3_get_table(db,UnicodeToUtf8(strAttackCountSql),&dbResult2,&nRow2,&nColumn2,&errMsg2);
											if(ret2==SQLITE_OK)
											{
												index2=nColumn2;
												for(i2=0;i2<nRow2;i2++)
												{
													for ( j2=0;j2<nColumn2;j2++)
													{
														int dwAttackCount;
														dwAttackCount= atoi(dbResult2[index2]);
														if(dwAttackCount>=3)
														{
															isAttack=TRUE;
															strAttackCount.Format(_T("%d"),dwAttackCount);
															CString strIsSucessCount;
															strIsSucessCount.Format(_T("SELECT count(*) from database_logon_log where logon_ip='%s' and logon_time='%s'and  logon_name='%s'and database_type ='%s'and is_logon_sucess='%s'"),strTempIP,strLogon_time,strLogonName,strDbType,_T("成功"));
															ret3=sqlite3_get_table(db,UnicodeToUtf8(strIsSucessCount),&dbResult3,&nRow3,&nColumn3,&errMsg3);
															if(ret3==SQLITE_OK)
															{
																index3=nColumn3;
																for(i3=0;i3<nRow3;i3++)
																{
																	for ( j3=0;j3<nColumn3;j3++)
																	{
																		int intCount;
																		intCount=atoi(dbResult3[index3]);
																		if(intCount>=1)
																		{
																			bIsSucess=TRUE;
																			break;
																		}
																		else
																		{
																			continue;
																		}
																		index3++;
																	}
																	if(bIsSucess==TRUE)
																	{
																		break;
																	}
																}
																sqlite3_free_table(dbResult3);
															}

														}
														index2++;
													}
													if(bIsSucess==TRUE)
													{
														break;
													}
												}
												sqlite3_free_table(dbResult2);
											}
											index1++;
										}

										if(bIsSucess==TRUE)
										{
											break;
										}
									}

									sqlite3_free_table(dbResult1);

								}
								index++;
							}
							if(isAttack)
							{
								isAttack=FALSE;
								char ** dbRs;
								int nR,nC;
								int ind;
								char * Msg;
								CString strGetAttackCout;
								CString strInsertblast_statisticalSql;
								ATTACKIPANALYSIS attackIPstruct;
								EVENT_ASSOCIATION_ANALYSIS eventstruct;
								strGetAttackCout=_T("");
								strGetAttackCout.Format(_T("SELECT count (*) from database_logon_log where logon_ip='%s' and logon_name='%s'and database_type ='%s'"),strTempIP,strLogonName,strDbType);
								int rs=sqlite3_get_table(db,UnicodeToUtf8(strGetAttackCout),&dbRs,&nR,&nC,&Msg);
								if(rs==SQLITE_OK)
								{
									ind=nC;
									for(int ii=0;ii<nR;ii++)
									{
										for ( int jj=0;jj<nC;jj++)
										{
											strAttackCount=UTF82WCS(dbRs[ind]);
											ind++;
										}
									}
									sqlite3_free_table(dbRs);
								}
								CString strMinSql,strMaxSql;
								strMinSql.Format(_T("SELECT MIN(logon_time) from database_logon_log where logon_ip='%s' and logon_name='%s'and database_type ='%s'"),strTempIP,strLogonName,strDbType);
								rs=sqlite3_get_table(db,UnicodeToUtf8(strMinSql),&dbRs,&nR,&nC,&Msg);
								if(rs==SQLITE_OK)
								{
									ind=nC;
									for(int ii=0;ii<nR;ii++)
									{
										for ( int jj=0;jj<nC;jj++)
										{
											strAttackBegin_time=UTF82WCS(dbRs[ind]);
											ind++;
										}
									}
									sqlite3_free_table(dbRs);
								}
								strMaxSql.Format(_T("SELECT MAX(logon_time) from database_logon_log where logon_ip='%s' and logon_name='%s'and database_type ='%s'"),strTempIP,strLogonName,strDbType);
								rs=sqlite3_get_table(db,UnicodeToUtf8(strMaxSql),&dbRs,&nR,&nC,&Msg);
								if(rs==SQLITE_OK)
								{
									ind=nC;
									for(int ii=0;ii<nR;ii++)
									{
										for ( int jj=0;jj<nC;jj++)
										{
											strAttackEnd_time=UTF82WCS(dbRs[ind]);
											ind++;
										}
									}
									sqlite3_free_table(dbRs);
								}
								if(bIsSucess==TRUE)
								{


									attackIPstruct.attack_event_name=_T("05001");
									eventstruct.attack_name=_T("05001");
									IsSucces=_T("成功");
									strInsertblast_statisticalSql.Format(_T("insert into dblog_blast_statistical values('%s', '%s', '%s', '%s', '%s','%s', '%s','%s','%s','%s')"),NewGUID(),strLogonName , strAttackBegin_time,strAttackEnd_time, strAttackCount,IsSucces,strTempIP,strDbType,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);

									bIsSucess=FALSE;
									//break;
								}
								else
								{
									attackIPstruct.attack_event_name=_T("05002");
									eventstruct.attack_name=_T("05002");
									IsSucces=_T("失败");
									strInsertblast_statisticalSql.Format(_T("insert into dblog_blast_statistical values('%s', '%s', '%s', '%s', '%s','%s', '%s','%s','%s','%s')"),NewGUID(),strLogonName , strAttackBegin_time,strAttackEnd_time, strAttackCount,IsSucces,strTempIP,strDbType,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
								}
								char *sql = UnicodeToUtf8(strInsertblast_statisticalSql);

								char *errMsg = NULL;

								int ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
								if(errMsg != NULL)
								{

									sqlite3_free(errMsg);
									//exit(-6);
								}
								if(sql)
								{
									delete []sql;
								}

								attackIPstruct.host_ip=CTOOLBOX4App::ms_strIP;
								attackIPstruct.attack_ip=strTempIP;
								if(strAttackBegin_time==strAttackEnd_time)
								{
									attackIPstruct.attack_begin_time=_T("");
									eventstruct.attack_time_begin=_T("");
								}
								else
								{
									attackIPstruct.attack_begin_time=strAttackBegin_time;
									eventstruct.attack_time_begin=strAttackBegin_time;
								}
								attackIPstruct.attack_end_time=strAttackEnd_time;

								InsertAttackIpData(attackIPstruct,db);


								eventstruct.attack_ip=strTempIP;

								eventstruct.host_ip=CTOOLBOX4App::ms_strIP;

								eventstruct.attack_time_end=strAttackEnd_time;
								Insertevent_association_analysis(eventstruct,db);
							}
						}
						sqlite3_free_table(dbResult);
					}

					index5++;
				} 
			}
			sqlite3_free_table(dbResult5);
		}
		sqlite3_exec(db,"commit;",0,0,0);
	}
	else if(strDbType==_T("MongoDB"))
	{


		int ret,ret1,ret2,ret3,ret5;
		char ** dbResult = NULL;
		char ** dbResult1 = NULL;
		BOOL IsInsert=FALSE;

		char * errMsg = NULL;
		char ** dbResult2 = NULL;
		char ** dbResult3 = NULL;
		char ** dbResult4 = NULL;
		char ** dbResult5 = NULL;
		int nRow, nRow1,nRow2,nRow3,nRow5;
		int nColumn, nColumn1,nColumn2,nColumn3,nColumn5;
		int index, index1,index2,index3,index5;
		int i1,i2,i3,i5,j1,j2,j3,j5;
		char * errMsg1 = NULL;
		char * errMsg2 = NULL;
		char * errMsg3 = NULL;
		char * errMsg4 = NULL;
		char * errMsg5 = NULL;


		CString strSql;
		CString cField;
		CString strPrcid;
		CString strTime;
		CString strText;
		CString strLogonName;
		CString strLogonIP;
		CString strDataBaseID;
		sqlite3_exec(db,"begin;",0,0,0);
		CString strSelectSql;
		CString strAttackCount;
		CString IsSucces;
		CString strAttackBegin_time;
		CString strAttackEnd_time;
		CString strGetUserNameSql;
		BOOL isAttack=FALSE;
		//CString strLogonName;
		strGetUserNameSql.Format(_T("SELECT DISTINCT logon_name from database_logon_log where database_type ='%s'"),strDbType);
		BOOL bIsSucess;
		ret5=sqlite3_get_table(db,UnicodeToUtf8(strGetUserNameSql),&dbResult5,&nRow5,&nColumn5,&errMsg5);
		if(ret5==SQLITE_OK)
		{
			index5=nColumn5;
			for(i5=0;i5<nRow5;i5++)
			{
				for ( j5=0;j5<nColumn5;j5++)
				{
					strLogonName=UTF82WCS(dbResult5[index5]);
					strSelectSql.Format(_T("SELECT DISTINCT logon_ip from database_logon_log where logon_name='%s'and database_type ='%s'"),strLogonName,strDbType);
					ret = sqlite3_get_table(db, UnicodeToUtf8(strSelectSql), &dbResult, &nRow,&nColumn, &errMsg);
					if(ret==SQLITE_OK)
					{
						CString strTempIP;
						index = nColumn;
						for (int i = 0; i < nRow; i++)
						{
							for (int j=0;j<nColumn;j++)
							{
								strTempIP = UTF82WCS(dbResult[index]);
								if(strTempIP.CompareNoCase(_T("127.0.0.1"))==0)
								{
									index++;
									continue;
								}
								CString strSelectTime;
								strSelectTime.Format(_T("SELECT DISTINCT logon_time from database_logon_log where logon_ip ='%s'and  logon_name='%s'and database_type ='%s'"),strTempIP,strLogonName,strDbType);
								ret1= sqlite3_get_table(db,UnicodeToUtf8(strSelectTime),&dbResult1,&nRow1,&nColumn1,&errMsg1);
								if(ret1==SQLITE_OK)
								{
									index1=nColumn1;
									for(i1=0;i1<nRow1;i1++)
									{
										for ( j1=0;j1<nColumn1;j1++)
										{
											CString strLogon_time;
											strLogon_time=UTF82WCS(dbResult1[index1]);
											CString strAttackCountSql;
											strAttackCountSql.Format(_T("SELECT count (*) from database_logon_log where logon_ip='%s' and logon_time='%s'and  logon_name='%s'and database_type ='%s'"),strTempIP,strLogon_time,strLogonName,strDbType);
											ret2=sqlite3_get_table(db,UnicodeToUtf8(strAttackCountSql),&dbResult2,&nRow2,&nColumn2,&errMsg2);
											if(ret2==SQLITE_OK)
											{
												index2=nColumn2;
												for(i2=0;i2<nRow2;i2++)
												{
													for ( j2=0;j2<nColumn2;j2++)
													{
														int dwAttackCount;
														dwAttackCount= atoi(dbResult2[index2]);
														if(dwAttackCount>=3)
														{
															isAttack=TRUE;
															strAttackCount.Format(_T("%d"),dwAttackCount);
															CString strLogon_Rs ,strLogonRsSql;
															strLogonRsSql.Format(_T("SELECT DISTINCT is_logon_sucess from database_logon_log where logon_ip='%s'and logon_name='%s'and database_type ='%s'"),strTempIP,strLogonName,strDbType);
															ret3=sqlite3_get_table(db,UnicodeToUtf8(strLogonRsSql),&dbResult3,&nRow3,&nColumn3,&errMsg3);
															if(ret3==SQLITE_OK)
															{
																index3=nColumn3;
																for(i3=0;i3<nRow3;i3++)
																{
																	for ( j3=0;j3<nColumn3;j3++)
																	{
																		CString strLogon_Rs;
																		strLogon_Rs=UTF82WCS(dbResult3[index3]);
																		if(strLogon_Rs==_T("成功"))
																		{
																			bIsSucess=TRUE;
																			break;
																		}
																		index3++;
																	}
																	
																}
																sqlite3_free_table(dbResult3);
															}

														}
														index2++;
													}
													if(bIsSucess==TRUE)
													{
														break;
													}
												}
												sqlite3_free_table(dbResult2);
											}
											index1++;
										}

										if(bIsSucess==TRUE)
										{
											break;
										}
									}

									sqlite3_free_table(dbResult1);

								}
								index++;
							}
							if(isAttack)
							{
								isAttack=FALSE;
								char ** dbRs;
								int nR,nC;
								int ind;
								char * Msg;
								CString strGetAttackCout;
								CString strInsertblast_statisticalSql;
								ATTACKIPANALYSIS attackIPstruct;
								EVENT_ASSOCIATION_ANALYSIS eventstruct;
								strGetAttackCout=_T("");
								strGetAttackCout.Format(_T("SELECT count (*) from database_logon_log where logon_ip='%s' and logon_name='%s'and database_type ='%s'"),strTempIP,strLogonName,strDbType);
								int rs=sqlite3_get_table(db,UnicodeToUtf8(strGetAttackCout),&dbRs,&nR,&nC,&Msg);
								if(rs==SQLITE_OK)
								{
									ind=nC;
									for(int ii=0;ii<nR;ii++)
									{
										for ( int jj=0;jj<nC;jj++)
										{
											strAttackCount=UTF82WCS(dbRs[ind]);
											ind++;
										}
									}
									sqlite3_free_table(dbRs);
								}
								CString strMinSql,strMaxSql;
								strMinSql.Format(_T("SELECT MIN(logon_time) from database_logon_log where logon_ip='%s' and logon_name='%s'and database_type ='%s'"),strTempIP,strLogonName,strDbType);
								rs=sqlite3_get_table(db,UnicodeToUtf8(strMinSql),&dbRs,&nR,&nC,&Msg);
								if(rs==SQLITE_OK)
								{
									ind=nC;
									for(int ii=0;ii<nR;ii++)
									{
										for ( int jj=0;jj<nC;jj++)
										{
											strAttackBegin_time=UTF82WCS(dbRs[ind]);
											ind++;
										}
									}
									sqlite3_free_table(dbRs);
								}
								strMaxSql.Format(_T("SELECT MAX(logon_time) from database_logon_log where logon_ip='%s' and logon_name='%s'and database_type ='%s'"),strTempIP,strLogonName,strDbType);
								rs=sqlite3_get_table(db,UnicodeToUtf8(strMaxSql),&dbRs,&nR,&nC,&Msg);
								if(rs==SQLITE_OK)
								{
									ind=nC;
									for(int ii=0;ii<nR;ii++)
									{
										for ( int jj=0;jj<nC;jj++)
										{
											strAttackEnd_time=UTF82WCS(dbRs[ind]);
											ind++;
										}
									}
									sqlite3_free_table(dbRs);
								}
								if(bIsSucess==TRUE)
								{


									attackIPstruct.attack_event_name=_T("05001");
									eventstruct.attack_name=_T("05001");
									IsSucces=_T("成功");
									strInsertblast_statisticalSql.Format(_T("insert into dblog_blast_statistical values('%s', '%s', '%s', '%s', '%s','%s', '%s','%s','%s','%s')"),NewGUID(),strLogonName , strAttackBegin_time,strAttackEnd_time, strAttackCount,IsSucces,strTempIP,strDbType,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);

									bIsSucess=FALSE;
									//break;
								}
								else
								{
									attackIPstruct.attack_event_name=_T("05002");
									eventstruct.attack_name=_T("05002");
									IsSucces=_T("失败");
									strInsertblast_statisticalSql.Format(_T("insert into dblog_blast_statistical values('%s', '%s', '%s', '%s', '%s','%s', '%s','%s','%s','%s')"),NewGUID(),strLogonName , strAttackBegin_time,strAttackEnd_time, strAttackCount,IsSucces,strTempIP,strDbType,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
								}
								char *sql = UnicodeToUtf8(strInsertblast_statisticalSql);

								char *errMsg = NULL;

								int ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
								if(errMsg != NULL)
								{

									sqlite3_free(errMsg);
									//exit(-6);
								}
								if(sql)
								{
									delete []sql;
								}

								attackIPstruct.host_ip=CTOOLBOX4App::ms_strIP;
								attackIPstruct.attack_ip=strTempIP;
								if(strAttackBegin_time==strAttackEnd_time)
								{
									attackIPstruct.attack_begin_time=_T("");
									eventstruct.attack_time_begin=_T("");
								}
								else
								{
									attackIPstruct.attack_begin_time=strAttackBegin_time;
									eventstruct.attack_time_begin=strAttackBegin_time;
								}
								attackIPstruct.attack_end_time=strAttackEnd_time;

								InsertAttackIpData(attackIPstruct,db);


								eventstruct.attack_ip=strTempIP;

								eventstruct.host_ip=CTOOLBOX4App::ms_strIP;

								eventstruct.attack_time_end=strAttackEnd_time;
								Insertevent_association_analysis(eventstruct,db);
							}
						}
						sqlite3_free_table(dbResult);
					}

					index5++;
				} 
			}
			sqlite3_free_table(dbResult5);
		}
		sqlite3_exec(db,"commit;",0,0,0);
	}
}
// 可疑账户, 攻击时间范围内创建的账户判断为可疑账户
void CLogAnalyze::SusAccount(sqlite3 *db)
{;
 	int ret;

	// 已经标记为可疑的账户
	vector<CString> vt_susAccount;
	vector<CString>::iterator it2;

	CString strIp_id = _T("");
	CString strTime = _T("");
	CString strName = _T("");

	char ** dbResult = NULL;
	int nRow, nColumn;
	char * errMsg = NULL;
	int index;
	char ** dbResult2 = NULL;
	int nRow2, nColumn2;
	int index2;
	char * errMsg2 = NULL;

	vector<USERINFO>vt_Account;
	USERINFO UserInfolist;
	set<SUSPICIOUSUSERINFO>suUserInfoLists;
	SUSPICIOUSUSERINFO suUserInfoList;
	vector<USERINFO>::iterator it;
	set<SUSPICIOUSUSERINFO>::iterator suit;

	const char *getlocalusername ="SELECT DISTINCT username FROM local_user_table";
	ret =sqlite3_get_table(db, getlocalusername, &dbResult, &nRow, &nColumn, &errMsg);
	{
		if(ret == SQLITE_OK)
		{
			index = nColumn;
			for (int i = 0; i < nRow; i++)
			{
				CString username =UTF82WCS(dbResult[index]);
				UserInfolist.strUserName=username;
				UserInfolist.intExist=1;
				vt_Account.push_back(UserInfolist);
				index++;
			}
		}
	}
	sqlite3_free_table(dbResult);
	if(errMsg!=NULL)
	{
		sqlite3_free(errMsg);
	}
	BOOL isExist=TRUE;
	//获取用户创建表里的用户名，如果存在本地用户里则存在，反之不存在
	const char * getusernamesql="SELECT DISTINCT taget_username FROM user_analysis";
	dbResult=NULL;
	ret = sqlite3_get_table(db, getusernamesql, &dbResult, &nRow, &nColumn, &errMsg);
	index=0;
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (int i = 0; i < nRow; i++)
		{
			isExist=TRUE;
			CString username =UTF82WCS(dbResult[index]);
			for(it = vt_Account.begin(); it != vt_Account.end(); it++)
			{
				CString Account = it->strUserName;
				if(Account==username)
				{
					isExist=FALSE;
					break;
				}
			}
			index++;
			if(isExist)
			{
				UserInfolist.strUserName=username;
				UserInfolist.intExist=0;
				vt_Account.push_back(UserInfolist);
			}
		}
	}
	sqlite3_free_table(dbResult);
	if(errMsg!=NULL)
		sqlite3_free(errMsg);
	std::vector<CString> v_Time;//创建时间范围
	//比较用户名是否含有可疑用户名表里的用户名，如果在表中存在则为可疑用户
	const char * getsuspicioussql="SELECT DISTINCT AccountName FROM Accountlist";
	dbResult=NULL;
	ret = sqlite3_get_table(db, getsuspicioussql, &dbResult, &nRow, &nColumn, &errMsg);
	index=0;
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (int i = 0; i < nRow; i++)
		{
			isExist=TRUE;
			CString username =UTF82WCS(dbResult[index]);
			for(it = vt_Account.begin(); it != vt_Account.end(); it++)
			{
				CString Account = it->strUserName;
				if(Account==username)
				{
					suUserInfoList.strUserName=it->strUserName;
					suUserInfoList.intExist=it->intExist;
					CString strGetCreateTimeSql;
					strGetCreateTimeSql.Format(_T("SELECT create_time FROM user_analysis where taget_username ='%s'and flag ='0'"),Account);
					char * getcreatetime=UnicodeToUtf8(strGetCreateTimeSql);
					int ret1=sqlite3_get_table(db, getcreatetime, &dbResult2, &nRow2, &nColumn2, &errMsg2);
					CString strCreateTime;
					if (ret1==SQLITE_OK)
					{
						index2 =nColumn2;
						
						for(int j=0;j<nRow2;j++)
						{
							if(nRow2>1)
							{
								CString CreateTime=UTF82WCS(dbResult2[index2]);
								v_Time.push_back(CreateTime);
							}
							else
							{
								CString CreateTime=UTF82WCS(dbResult2[index2]);
								strCreateTime=CreateTime;
							}
							index2++;
						}
						if (v_Time.size()>1)
						{
							auto maxIt = max_element(v_Time.begin(), v_Time.end());
							TCHAR lastTime[32];
							memset(lastTime,0,32);
							_tcscpy_s(lastTime, *maxIt);
							strCreateTime.Format(_T("%s"),lastTime);
						}
					}
					sqlite3_free_table(dbResult2);
					if(errMsg2!=NULL)
						sqlite3_free(errMsg2);
					suUserInfoList.strCreateTime=strCreateTime;
					CString strGetusernameSql;
					strGetusernameSql.Format(_T("SELECT username FROM user_analysis where taget_username ='%s'and flag ='0'"),Account);
					char * getusername=UnicodeToUtf8(strGetusernameSql);
					dbResult2=NULL;
					ret1=sqlite3_get_table(db, getusername, &dbResult2, &nRow2, &nColumn2, &errMsg2);
					
					CString strUsername;
					
					set<CString> usernames;
					if (ret1==SQLITE_OK)
					{
						index2 =nColumn2;

						for(int j=0;j<nRow2;j++)
						{
							if(nRow2>1)
							{
								CString username=UTF82WCS(dbResult2[index2]);
								usernames.insert(username);
							}
							else
							{
								CString username=UTF82WCS(dbResult2[index2]);
								strUsername=username;
							}
							index2++;
						}
						set<CString> ::iterator it;
						for (it=usernames.begin();it!=usernames.end();it++)
						{
							CString str=*it;
							if(usernames.size()==1)
							{
								strUsername=str;
							}
							else
							{
								strUsername=strUsername+str+_T(",");
							}
							
						}
						
					}
					sqlite3_free_table(dbResult2);
					if (errMsg2!=NULL)
					{
						sqlite3_free(errMsg2);
					}
					suUserInfoList.strCreateUserName=strUsername;
					suUserInfoLists.insert(suUserInfoList);
					break;
				}
			}
			index++;
			
		}
	}
	sqlite3_free_table(dbResult);
	if(errMsg!=NULL)
		sqlite3_free(errMsg);
	//获取攻击IP表中的攻击时间范围，比较用户创建时间是否在攻击时间范围内，如果存在则为可疑用户
	const char * getanalysisIPV_time="SELECT attack_time_begin, attack_time_end from Source_Ip_Analysis";
	ret = sqlite3_get_table(db, getanalysisIPV_time, &dbResult, &nRow, &nColumn, &errMsg);
	std::vector<CString> v_TimeIP;//可疑IP攻击时间范围
	TCHAR AttackBeginTime[32];
	//memset(AttackBeginTime,0,32);
	TCHAR AttackEndTime[32];
	//memset(AttackEndTime,0,32);
	CString strAttackBeginTime;
	CString strAttackEndTime;
	index=0;
	CString cField;
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (int i = 0; i < nRow; i++)
		{
			for (int j=0;j<nColumn;j++)
			{
				cField = UTF82WCS(dbResult[j]);
				if(cField==_T("attack_time_begin"))
				{
					CString strBeginTime = UTF82WCS(dbResult[index]);
					v_TimeIP.push_back(strBeginTime);
				}
				else if(cField==_T("attack_time_end"))
				{
					CString strEndTime = UTF82WCS(dbResult[index]);
					v_TimeIP.push_back(strEndTime);
				}
				
			}
			index++;
		}
	}
	sqlite3_free_table(dbResult);
	if(errMsg!=NULL)
	sqlite3_free(errMsg);
	if(v_TimeIP.size()>0)
	{
		auto maxIt = max_element(v_TimeIP.begin(), v_TimeIP.end());
		auto minIt= min_element(v_TimeIP.begin(), v_TimeIP.end());
		_tcscpy_s(AttackEndTime, *maxIt);
		_tcscpy_s(AttackBeginTime, *minIt);
		CString strtaget_username;
		CString strusername;
		CString strCreateTime;
		strAttackEndTime.Format(_T("%s"),AttackEndTime);
		strAttackBeginTime.Format(_T("%s"),AttackBeginTime);
		const char *GetCreateUserInfosql="SELECT DISTINCT taget_username ,username,create_time FROM user_analysis";
		ret = sqlite3_get_table(db, GetCreateUserInfosql, &dbResult, &nRow, &nColumn, &errMsg);
		if(ret == SQLITE_OK)
		{
			index = nColumn;
			for (int i = 0; i < nRow; i++)
			{
				for (int j=0;j<nColumn;j++)
				{
					cField = UTF82WCS(dbResult[j]);
					if(cField==_T("taget_username"))
					{
						strtaget_username = UTF82WCS(dbResult[index]);
						
					}
					else if(cField==_T("username"))
					{
						strusername = UTF82WCS(dbResult[index]);
						
					}
					else
					{
						strCreateTime=UTF82WCS(dbResult[index]);
						if(strCreateTime<strAttackEndTime &&strCreateTime>strAttackBeginTime)
						{
							suUserInfoList.strUserName=strtaget_username;
							suUserInfoList.strCreateUserName=strusername;
							suUserInfoList.strCreateTime=strCreateTime;
							suUserInfoLists.insert(suUserInfoList);
						}
					}
				index++;
				}
				
			}
		}
		sqlite3_free_table(dbResult);
		if (errMsg!=NULL)
		{
			sqlite3_free(errMsg);
		}
	}
	//没有攻击范围时间则认为创建的用户全部为可疑用户
	else
	{
		CString strtaget_username;
		CString strusername;
		CString strCreateTime;
	
		const char *GetCreateUserInfosql="SELECT DISTINCT taget_username ,username,create_time FROM user_analysis";
		ret = sqlite3_get_table(db, GetCreateUserInfosql, &dbResult, &nRow, &nColumn, &errMsg);
		if(ret == SQLITE_OK)
		{
			index = nColumn;
			for (int i = 0; i < nRow; i++)
			{
				for (int j=0;j<nColumn;j++)
				{
					cField = UTF82WCS(dbResult[j]);
					if(cField==_T("taget_username"))
					{
						strtaget_username = UTF82WCS(dbResult[index]);

					}
					else if(cField==_T("username"))
					{
						strusername = UTF82WCS(dbResult[index]);

					}
					else
					{
						strCreateTime=UTF82WCS(dbResult[index]);
						//if(strCreateTime<strAttackEndTime &&strCreateTime>strAttackBeginTime)
						{
							suUserInfoList.strUserName=strtaget_username;
							suUserInfoList.strCreateUserName=strusername;
							suUserInfoList.strCreateTime=strCreateTime;
							suUserInfoLists.insert(suUserInfoList);
						}
					}
				index++;
				}
				
			}
		}
		sqlite3_free_table(dbResult);
		if (errMsg!=NULL)
		{
			sqlite3_free(errMsg);
		}
	}
	//最后判定可疑用户是否存在
	set<SUSPICIOUSUSERINFO> suUserInfos;
	SUSPICIOUSUSERINFO suUserInfo;
	BOOL suIsExist=TRUE;
	for (suit=suUserInfoLists.begin();suit!=suUserInfoLists.end();suit++)
	{
		CString username=suit->strUserName;
		for(it = vt_Account.begin(); it != vt_Account.end(); it++)
		{
			CString Account = it->strUserName;
	
			if(Account==username)
			{
				suIsExist=FALSE;
				suUserInfo.strCreateTime=suit->strCreateTime;
				suUserInfo.strCreateUserName=suit->strCreateUserName;
				suUserInfo.strUserName=suit->strUserName;
				suUserInfo.intExist=it->intExist;
				suUserInfos.insert(suUserInfo);
			}
		}
	}
	set<SUSPICIOUSUSERINFO>::iterator suIt;
	for (suIt=suUserInfoLists.begin();suIt!=suUserInfoLists.end();suIt++)
	{
		CString strInsertSql;
		strInsertSql.Format(TEXT("insert into Suspicious_Account(")
			TEXT("suspicious_account_Id,")
			TEXT("source_ip_analysis_id,")
			TEXT("account_name,")
			TEXT("create_username,")
			TEXT("account_create_time,")
			TEXT("account_is_exist,")
			TEXT("mac_address,")
			TEXT("event_task_id) values('%s','%s','%s','%s','%s','%d','%s','%s')"),
			NewGUID(),
			_T(""),
			suIt->strUserName,
			suIt->strCreateUserName,
			suIt->strCreateTime,
			suIt->intExist,
			CTOOLBOX4App::ms_strMacAddr,
			CModule::m_csEventTaskId);
		char *insertsql;
		insertsql=UnicodeToUtf8(strInsertSql);
		char *errMsg7;
		int ret7 = sqlite3_exec(db, insertsql, NULL, NULL, &errMsg7);
		if(ret7 != SQLITE_OK)
		{
			OutputDebugString(_T("insert Suspicious_Account"));
			OutputDebugString(CString(errMsg7));
			sqlite3_free(errMsg7);
		}
		EVENT_ASSOCIATION_ANALYSIS eventstruct;
		eventstruct.host_ip=CTOOLBOX4App::ms_strIP;
		eventstruct.attack_name=_T("03001");
		eventstruct.attack_time_end=suIt->strCreateTime;
		eventstruct.login_name=suIt->strCreateUserName;
		eventstruct.suspicious_username=suIt->strUserName;
		//可疑账户创建
		Insertevent_association_analysis(eventstruct,db);
		eventstruct.host_ip=CTOOLBOX4App::ms_strIP;
		eventstruct.attack_name=_T("03002");
		eventstruct.attack_time_end=suIt->strCreateTime;
		eventstruct.login_name=suIt->strCreateUserName;
		eventstruct.suspicious_username=suIt->strUserName;
		//可疑账户启用
		Insertevent_association_analysis(eventstruct,db);
	}
}

// ip攻击时所登录的账户 从登录到注销的时间 都判定为此ip的攻击时间
void AttackIp_time(vector<p_IpTimeRange_>&vt)

{
	sqlite3 * m_hSql;
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;

	vector<p_IpTimeRange_>::iterator it;

	// 打开数据库
	CString Path1 = CTOOLBOX4App::ms_strFullResultPath;
	Path1 += _T("主机层\\hongtan004.db");

	char * pDbName = UnicodeToUtf8(Path1);//
	ret = sqlite3_open(pDbName, &m_hSql);
	if(ret != SQLITE_OK)
	{
		MessageBox(NULL, _T("数据库打开失败-SusAccount"), _T("错误"), MB_ICONERROR);
		exit(-19);
	}

	const char * sql1 = "select this_login_time, this_off_time from Safe_Log_Oper_Statistics";
	ret = sqlite3_get_table(m_hSql, sql1, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		CString login_time;
		CString off_time;
		for (i = 0; i < nRow; i++)
		{
			login_time = _T("");
			off_time = _T("");
			for (j = 0; j < nColumn; j++)
			{
				// 字段名: dbResult[j], 值: dbResult[index] ;
				if(UTF82WCS(dbResult[j]) == _T("this_login_time"))
				{
					login_time = UTF82WCS(dbResult[index]);
				}
				else if(UTF82WCS(dbResult[j]) == _T("this_off_time"))
				{
					off_time = UTF82WCS(dbResult[index]);
				}
				index++;
			}
			for(it = vt.begin(); it != vt.end(); it++)
			{
				CString ip_LastTime = (*it)->LastTime;
				// 如果ip的结束时间在此账户的登录时间(登录-注销)内, 就将此账户的注销时间当做ip的结束时间
				if(!off_time.IsEmpty() && ip_LastTime > login_time && ip_LastTime < off_time )
				{
					_tcsncpy_s((*it)->LastTime, off_time.GetBuffer(), 31);
				}
			}
		}
		sqlite3_free_table(dbResult);	// 释放结果
	}
	if(errMsg != NULL)
		sqlite3_free(errMsg);

	sqlite3_close(m_hSql);

}

/////////////////////////////////////////// 
// 判断文件是否有内容
bool FileIsContent(CString&fileName)
{
	ULONGLONG size;  
	CString strFilePath = fileName;  
	CFileStatus fileStatus; 

	CFile::GetStatus(strFilePath, fileStatus);
	size = fileStatus.m_size;

	return size>0;
}

// 从工具日志中查询IP 3
void SearchIpFromLog(vector<p_Ip_Tools>&vt, CString&FileName, CString Tool)
{
	vector<p_Ip_Tools>::iterator it;

	//////////内存映射
	HANDLE hFile = CreateFile(	
		FileName,					// 文件路径
		GENERIC_READ,				// 只读
		FILE_SHARE_READ,			// 只读共享
		nullptr,					// 默认安全属性
		OPEN_EXISTING,				// 只能打开已存在的文件,否则失败
		FILE_FLAG_SEQUENTIAL_SCAN,	// 对文件进行顺序操作而不是随机操作
		nullptr						// 一般为0
		);
	if(hFile == INVALID_HANDLE_VALUE)
	{
		DWORD errCode =  GetLastError();
		CString err;
		err.Format(_T("打开文件失败[%lu][%s]"), errCode, FileName);
		MessageBox(NULL, err, _T("错误"), MB_ICONERROR);
		exit(-23);
	}
	HANDLE hFileMap = CreateFileMapping(
		hFile,				// 文件对象句柄
		nullptr,			// 默认安全属性
		PAGE_READONLY,		// 页面保护,只读
		0,					// 需要的内存大小, 和打开的文件大小一样
		0,					// 
		nullptr				// 共享内存, 不需要,为null
		);
	if(!hFileMap)
	{
		MessageBox(NULL, _T("内存映射失败"), _T("错误"), MB_ICONERROR);
		exit(-24);
	}


	void *pBuffer = MapViewOfFile(
		hFileMap,			// 文件映射句柄
		FILE_MAP_READ,		// 映射文件只读
		0,					// 0 表示从文件开头读取
		0,					
		0					// 0 全部读取
		);
	if(!pBuffer)
	{
		CloseHandle(hFile);
		CloseHandle(hFileMap);
		AfxMessageBox(_T("文件映射失败"));
		exit(-25);
	}
	CloseHandle(hFile);
	char * cBuffer = (char *)pBuffer;
	for(it = vt.begin(); it != vt.end(); it++)
	{
		char * Ip = UnicodeToUtf8((*it)->Ip);
		if(strstr(cBuffer, Ip) != NULL)
		{
			(*it)->Tools += Tool;
			(*it)->Tools += _T(",");
		}
	}
	UnmapViewOfFile(pBuffer);
	CloseHandle(hFileMap);
}

//2
void SearchTools(vector<p_Ip_Tools>&vt)
{
	vector<p_Ip_Tools>::iterator it;

	CString RootPath = CTOOLBOX4App::ms_strFullResultPath;
	RootPath += _T("WebAttackAction\\");
	for(int i = 1; ;++i)
	{
		CString WepPath;
		WepPath.Format(_T("%sResult%d"), RootPath, i);
		if(IsDirExist(WepPath))
		{
			CString ToolsPath = WepPath + _T("\\WebScanner");
			CFileFind ff;
			CString fileFind = ToolsPath + _T("\\*.*");
			BOOL bFileExit = ff.FindFile(fileFind);
			while(bFileExit)
			{
				bFileExit = ff.FindNextFile();
				if( ff.GetFileName() == _T(".") || ff.GetFileName() == _T("..") || ff.IsDirectory())
				{
					continue;
				}
				CString strFileName = ff.GetFileName();//得到文件名
				CString strFile = ToolsPath + _T("\\") + strFileName;
				if(FileIsContent(strFile))
				{
					if(strFileName.Find(_T("Appscan")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("Appscan"));
					}
					else if(strFileName.Find(_T("AWVS")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("AWVS"));
					}
					else if(strFileName.Find(_T("BabyKrokodil")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("BabyKrokodil"));
					}
					else if(strFileName.Find(_T("dirbuster")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("dirbuster"));
					}
					else if(strFileName.Find(_T("havij")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("havij"));
					}
					else if(strFileName.Find(_T("httperf")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("httperf"));
					}
					else if(strFileName.Find(_T("HTTrack")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("HTTrack"));
					}
					else if(strFileName.Find(_T("hydra")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("hydra"));
					}
					else if(strFileName.Find(_T("Nessus")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("Nessus"));
					}
					else if(strFileName.Find(_T("Netsparker")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("Netsparker"));
					}
					else if(strFileName.Find(_T("Nikto")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("Nikto"));
					}
					else if(strFileName.Find(_T("nmap")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("nmap"));
					}
					else if(strFileName.Find(_T("owasp")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("owasp"));
					}
					else if(strFileName.Find(_T("pangolin")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("pangolin"));
					}
					else if(strFileName.Find(_T("Rsas")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("Rsas"));
					}
					else if(strFileName.Find(_T("SQLMap")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("SQLMap"));
					}
					else if(strFileName.Find(_T("w3af")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("w3af"));
					}
					else if(strFileName.Find(_T("Webinspect")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("Webinspect"));
					}
					else if(strFileName.Find(_T("zmeu")) != -1)
					{
						SearchIpFromLog(vt, strFile, _T("zmeu"));
					}
					
				}
				else
				{
					continue;
				}

			
			}
			ff.Close();
		}
		else
			break;
	}

}

// 查找IP是否使用攻击工具 1
 void IpTools()
{
	sqlite3 * m_hSql;
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;
	// 打开数据库
	CString Path1 = CTOOLBOX4App::ms_strFullResultPath;
	Path1 += _T("主机层\\hongtan004.db");

	char * pDbName = UnicodeToUtf8(Path1);//
	ret = sqlite3_open(pDbName, &m_hSql);
	if(ret != SQLITE_OK)
	{
		MessageBox(NULL, _T("数据库打开失败-07"), _T("错误"), MB_ICONERROR);
		exit(-19);
	}
	// 可疑IP
	vector<p_Ip_Tools> v_SusIp;
	vector<p_Ip_Tools>::iterator it;
	const char *sql="select distinct ip_address from Source_Ip_Analysis";

	ret = sqlite3_get_table(m_hSql, sql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				CString Ip = UTF82WCS(dbResult[index]);
				p_Ip_Tools pIpTools = new _Ip_Tools;
				//memset(pIpTools, 0, sizeof(_Ip_Tools));
				pIpTools->Ip = _T("");
				pIpTools->Tools = _T("");
				pIpTools->Ip = Ip;
				v_SusIp.push_back(pIpTools);
				index++;
			}
		}
		sqlite3_free_table(dbResult);	// 释放结果
	}
	if(errMsg!=NULL)
		sqlite3_free(errMsg);
	SearchTools(v_SusIp);

	char msql[256] = {0};
	for(it = v_SusIp.begin(); it != v_SusIp.end(); ++it)
	{
		memset(msql, 0, sizeof(msql));
		CString Guid =  NewGUID();
		_snprintf_s(msql, 255, "insert into Suspicious_Ip_Hacker values('%s', '%s', '%s', '%s', '%s')", UnicodeToUtf8(Guid), UnicodeToUtf8((*it)->Ip), UnicodeToUtf8((*it)->Tools), UnicodeToUtf8(CTOOLBOX4App::ms_strMacAddr), UnicodeToUtf8(CModule::m_csEventTaskId));
		ret = sqlite3_exec(m_hSql, msql, NULL, NULL, &errMsg);
		if(errMsg != NULL)
		{
			MessageBox(NULL, UTF82WCS(errMsg), _T("错误"), MB_ICONERROR);
			sqlite3_free(errMsg);
			exit(-6);
		}
	}

	sqlite3_close(m_hSql);
}

// PC资产  检查时间和中间件类型 写xml文件
void PC_TimeAndWebType(sqlite3*db)
{
	// 中间件类型
	CString WebType = _T(""); 

	sqlite3 * m_hSql = db;
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;
	// 打开数据库
	//CString Path1 = CTOOLBOX4App::ms_strFullResultPath;
	//Path1 += _T("主机层\\hongtan004.db");

	//char * pDbName = UnicodeToUtf8(Path1);//
	//ret = sqlite3_open(pDbName, &m_hSql);
	//if(ret != SQLITE_OK)
	//{
	//	MessageBox(NULL, _T("数据库打开失败-08"), _T("错误"), MB_ICONERROR);
	//	exit(-19);
	//}
	const char *sql = "select log_type from watchertrack_attack_record";
	ret = sqlite3_get_table(m_hSql, sql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				
				if(WebType.Find(UTF82WCS(dbResult[index])) == -1)// 不显示重复的中间件, 当>=0 说明中间件重复了.
				{
					if(!WebType.IsEmpty())
					{
						WebType += _T(",");
					}
					WebType += UTF82WCS(dbResult[index]);
				}
					
				index++;
			}
		}
		sqlite3_free_table(dbResult);	// 释放结果
	}
	if(errMsg!=NULL)
		sqlite3_free(errMsg);
	//sqlite3_close(m_hSql);
	OutputDebugString(_T("A1"));
	BOOL bl = FALSE;
	CString strUpdatesql;
	if(WebType.GetLength()==0)
	{
		return;
	}
	else
	{
		strUpdatesql.Format(_T("UPDATE Pc_Account set web_container ='%s'where mac_address ='%s'"),WebType,CTOOLBOX4App::ms_strMacAddr);
		char *Updatesql = UnicodeToUtf8(strUpdatesql);
		ret=sqlite3_exec(db, Updatesql, NULL, NULL, &errMsg);
		if(ret != SQLITE_OK)
		{
			delete []Updatesql;
			MessageBox(NULL, _T("数据库插入数据失败"), _T("错误"), MB_ICONERROR);
			return;
		}
		delete []Updatesql;
	}

//	GetPCTaiZhangEx(NULL,0,bl, WebType, CTOOLBOX4App::m_startTimeFull, db, CTOOLBOX4App::ms_strMacAddr, CModule::m_csEventTaskId);
	OutputDebugString(_T("A2"));

}

//void CLogAnalyze::ClearNetDeepRst()
//{
//	vector<PNETDEEPRESULT>::iterator it;
//	for(it = CDisposeResult::m_vNetDeepResult.begin(); it != CDisposeResult::m_vNetDeepResult.end(); it++)
//	{
//		if((*it) != NULL)
//		{
//			delete *it;
//			*it = NULL;
//		}
//	}
//	CDisposeResult::m_vNetDeepResult.clear();
//}

//void CLogAnalyze::ClearUsbDeepRst()
//{
//	vector<PUSBDEEPRESULT>::iterator it;
//	for(it = CDisposeResult::m_vUsbDeepResult.begin(); it != CDisposeResult::m_vUsbDeepResult.end(); it++)
//	{
//		if(*it != NULL)
//		{
//			delete *it;
//			*it = NULL;
//		}
//	}
//	CDisposeResult::m_vUsbDeepResult.clear();
//}

/*
// 联网痕迹-深度 采集结果写xml文件, 写完清空容器
void NetDeepRstToXml()
{
	CYunDunUtility util;
	util.SetXMLFile(_T("主机层\\SystemInfoResult.ydxml"));
	vector<map<string,CString>> Vt;
	vector<PNETDEEPRESULT>::iterator it;
	for(it = CDisposeResult::m_vNetDeepResult.begin(); it != CDisposeResult::m_vNetDeepResult.end(); it++)
	{
		map<string,CString> map1;
		map1.insert(pair<string,CString>("net_open_time", (*it)->strTime));
		map1.insert(pair<string,CString>("net_url", (*it)->strDesc));
		Vt.push_back(map1);
	}
	util.WriteVector2XMLFile(Vt,"Net_Deep_Check");
	CLogAnalyze::ClearNetDeepRst();
}
*/
/*
// 介质痕迹-深度 采集结果写xml文件, 写完清空容器
void UsbDeepRstToXml()
{
	CYunDunUtility util;
	util.SetXMLFile(_T("主机层\\SystemInfoResult.ydxml"));
	vector<map<string,CString>> Vt;
	vector<PUSBDEEPRESULT>::iterator it;
	for(it = CDisposeResult::m_vUsbDeepResult.begin(); it != CDisposeResult::m_vUsbDeepResult.end(); it++)
	{
		map<string,CString> map1;
		map1.insert(pair<string,CString>("usb_sn", (*it)->usb_id));
		map1.insert(pair<string,CString>("usb_name", (*it)->usb_name));
		map1.insert(pair<string,CString>("type", (*it)->usb_type));
		map1.insert(pair<string,CString>("last_time", (*it)->usb_time));
		map1.insert(pair<string,CString>("first_time", (*it)->usb_firsttime));
		map1.insert(pair<string,CString>("pid", (*it)->usb_PID));
		map1.insert(pair<string,CString>("vid", (*it)->usb_VID));
		Vt.push_back(map1);
	}
	util.WriteVector2XMLFile(Vt,"Usb_Deep");
	CLogAnalyze::ClearUsbDeepRst();
}
*/
// *综合分析

void InsertPrivilege(sqlite3*db, CString Server, CString ServerName, CString Priv)
{
	CString Sql;
	CString uuid = NewGUID();
	Sql.Format(_T("insert into Sensitive_Authority values('%s', '%s', '%s', '%s', '%s')"), uuid, Server, ServerName, Priv);
	char *cSql = UnicodeToUtf8(Sql);
	char *errMsg;
	int ret = sqlite3_exec(db, cSql, NULL, NULL, &errMsg);
	if(ret != SQLITE_OK)
	{
		delete []cSql;
		MessageBox(NULL, _T("数据库插入数据失败"), _T("错误"), MB_ICONERROR);
		return;
	}
	delete []cSql;
	return;
}

// 将敏感权限使用(4673)日志入库
void Privilege()
{
	CString CSQPath = CTOOLBOX4App::ms_strFullResultPath;
	CSQPath += _T("主机层\\hongtan004.db");

	char * pDbName = UnicodeToUtf8(CSQPath);

	sqlite3 * hSql;
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;

	ret = sqlite3_open(pDbName, &hSql);
	if(ret != SQLITE_OK)
	{
		MessageBox(NULL, _T("数据库打开失败-SusAccount"), _T("错误"), MB_ICONERROR);
		exit(-30);
	}

	CString desc;
	CString strTemp;

	CString Server;
	CString ServerName;
	CString Priv;

	const char *Sql = "select * from Win_Sec_Log where event_id = '4673'";
	ret = sqlite3_get_table(hSql, Sql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				if(strcmp(dbResult[j], "describe"))
				{
					 desc = UTF82WCS(dbResult[index]);
					 Server = _T("");
					 ServerName = _T("");
					 Priv = _T("");
					 while(!desc.IsEmpty())
					 {
						 if(desc.Find(_T('|')) >= 0)
						 {
							 strTemp = desc.Left(desc.Find(_T('|')));
							 if(strTemp.Find(_T("服务器:")) >= 0)
							 {
								 strTemp.Right(strTemp.GetLength()-strTemp.Find(_T(':'))-1);
								 strTemp.TrimLeft();
								 Server = strTemp;
							 }
							 else if(strTemp.Find(_T("服务名:")) >= 0)
							 {
								 strTemp.Right(strTemp.GetLength()-strTemp.Find(_T(':'))-1);
								 strTemp.TrimLeft();
								 ServerName = strTemp;
							 }
							 else if(strTemp.Find(_T("特权:")) >= 0)
							 {
								 strTemp.Right(strTemp.GetLength()-strTemp.Find(_T(':'))-1);
								 strTemp.TrimLeft();
								 Priv = strTemp;

								 InsertPrivilege(hSql, Server, ServerName, Priv);
								 break;
							 }
							 desc = desc.Right(desc.GetLength()-desc.Find(_T('|'))-1);
						 }
						 else
						 {
							 if(desc.Find(_T("特权:")) >= 0)
							 {
								 desc = desc.Right(desc.GetLength()-desc.Find(_T(':'))-1);
								 desc.TrimLeft();
								 Priv = desc;
								 InsertPrivilege(hSql, Server, ServerName, Priv);
								 break;
							 }
						 }
					 }
				}
				index++;
			}
		}
		sqlite3_free_table(dbResult);	// 释放结果
	}
	if(errMsg!=NULL)
		sqlite3_free(errMsg);
	sqlite3_close(hSql);


}

// 获取表中记录的条数.
int GetTableCount1(sqlite3*db, const char *table)
{
	int count = 0;
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;
	char sql[1024];
	memset(sql, 0, sizeof(sql));
	_snprintf_s(sql, 1024, "select count(*) from %s", table);
	ret = sqlite3_get_table(db, sql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				count = atoi(dbResult[index]);
				index++;
			}
		}
		sqlite3_free_table(dbResult);	// 释放结果
	}
	if(errMsg!=NULL)
	sqlite3_free(errMsg);

	return count;
}

int GetTableCount2(sqlite3*db, const char *sql)
{
	int count = 0;
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;

	ret = sqlite3_get_table(db, sql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				count = atoi(dbResult[index]);
				index++;
			}
		}
		sqlite3_free_table(dbResult);	// 释放结果
	}
	if(errMsg!=NULL)
	sqlite3_free(errMsg);

	return count;
}

void InsertEventJudgment(sqlite3 *db, char *Mac, char *ip, char*eventId, char *cProperty, char *cBasis)
{
	char *errMsg = NULL;
	char sql[1024];
	memset(sql, 0, sizeof(sql));
	char *uuid = UnicodeToUtf8(NewGUID());
	_snprintf_s(sql, 1024, "insert into Event_Property_Judgment(id, ip, event_property, judgment_basis, mac_address, event_task_id) values('%s', '%s', '%s', '%s', '%s', '%s')", 
		uuid, ip, cProperty, cBasis, Mac, eventId);
	int ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
	if(ret != SQLITE_OK)
	{
		OutputDebugString(_T("插入数据错误!"));
		OutputDebugString(CString(errMsg));
		sqlite3_free(errMsg);
	}

	return;
}

// Webshell是否包含图片类型 pCount:Webshell中包含的图片的数量.
BOOL IsWebshellIncludePhoto(sqlite3*db, int *pCount)
{
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;

	BOOL bRet = FALSE;
	int nCount = 0;
	CString temp;
	const char *sql = "select file_name from Other_Action where type = '1'";
	const TCHAR *type[4] = {_T("jpg"), _T("png"), _T("gif"), _T("bmp")};
	ret = sqlite3_get_table(db, sql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				temp = UTF82WCS(dbResult[index]);
				temp = temp.Right(3);
				for(int k = 0; k < 4; k++)
				{
					if(temp.CompareNoCase(type[k]) == 0)
					{
						bRet = TRUE;
						nCount++;
						break;
					}
				}
				index++;
			}
		}
		sqlite3_free_table(dbResult);	// 释放结果
	}
	if(errMsg!=NULL)
	sqlite3_free(errMsg);
	*pCount = nCount;

	return bRet;
}
int GetWebAttackCount(sqlite3 *db,char * code)
{
	int count = 0;
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;

	char sql[1024];
	memset(sql, 0, sizeof(sql));
	_snprintf_s(sql, 1024, "select count(*) from Web_Attack_Action where attack_code='%s'", code);
	ret = sqlite3_get_table(db, sql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				count = atoi(dbResult[index]);
				index++;
			}
		}
		sqlite3_free_table(dbResult);	// 释放结果
	}
	if(errMsg!=NULL)
		sqlite3_free(errMsg);

	return count;

}
//获取web层攻击
void GetWebAttack(sqlite3 *db,CString strSource_Ip, CString Mac, CString EventId)
{
	CString strsql;
	strsql.Format(_T("SELECT DISTINCT attack_code from Web_Attack_Action where attack_ip='%s'"),strSource_Ip);
	char* sql=UnicodeToUtf8(strsql);
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char ** dbResult1 = NULL;
	int nRow1, nColumn1;
	int i1, j1, index1;
	char ** dbResult2 = NULL;
	int nRow2, nColumn2;
	int i2, j2, index2;
	char ** dbResult3 = NULL;
	int nRow3, nColumn3;
	int i3, j3, index3;
	char * errMsg = NULL;
	ret = sqlite3_get_table(db, sql, &dbResult, &nRow, &nColumn, &errMsg);
	CString csFiled;
	CString strAttack_code;
	CString strAttackTime;
	CString strAttack_name;
	CString strEndTime,strBeginTime;
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				strAttack_code=UTF82WCS(dbResult[index]);
				CString strMaxTime,strMinTime;

				strMaxTime.Format(_T("SELECT MAX(attack_time) from Web_Attack_Action where attack_code='%s' and attack_ip='%s'"),strAttack_code,strSource_Ip) ;
				char * maxsql=UnicodeToUtf8(strMaxTime);
				strMinTime.Format(_T("SELECT min(attack_time) from Web_Attack_Action where attack_code='%s' and attack_ip='%s'"),strAttack_code,strSource_Ip) ;
				char * minsql=UnicodeToUtf8(strMinTime);
				ret = sqlite3_get_table(db, maxsql, &dbResult2, &nRow2, &nColumn2, &errMsg);
				if(ret==SQLITE_OK)
				{
					index2=nColumn2;
					for (i2 = 0; i2 < nRow2; i2++)
					{
						for (j2 = 0; j2 < nColumn2; j2++)
						{																
							strEndTime=UTF82WCS(dbResult2[index2]);

							index2++;

						}
					}
				}
				if(maxsql != NULL)
				{
					delete []maxsql;
					maxsql = NULL;
				}
				ret = sqlite3_get_table(db, minsql, &dbResult3, &nRow3, &nColumn3, &errMsg);
				if(ret==SQLITE_OK)
				{
					index3=nColumn3;
					for (i3 = 0; i3 < nRow3; i3++)
					{
						for (j3 = 0; j3 < nColumn3; j3++)
						{																
							strBeginTime=UTF82WCS(dbResult3[index3]);

							index3++;

						}
					}
				}
				if(minsql != NULL)
				{
					delete []minsql;
					minsql = NULL;
				}
				CString strselectsql;

				strselectsql.Format(_T("SELECT config_item_name from Data_Analysis_Config where config_item_code='%s'"),strAttack_code);
				char * selectsql=UnicodeToUtf8(strselectsql);
				ret = sqlite3_get_table(db, selectsql, &dbResult1, &nRow1, &nColumn1, &errMsg);
				strAttack_name=_T("");
				if(ret==SQLITE_OK)
				{
					index1=nColumn1;
					for (i1 = 0; i1 < nRow1; i1++)
					{
						for (j1 = 0; j1 < nColumn1; j1++)
						{
							strAttack_name=UTF82WCS(dbResult1[index1]);

							index1++;

						}
					}
				}
				if(selectsql != NULL)
				{
					delete []selectsql;
					selectsql = NULL;
				}
			}
			index++;
			CString strInsertSql;
			CString strUid;
			strUid=NewGUID();
			strAttackTime=strBeginTime;
			strAttackTime+=_T("~");
			strAttackTime+=strEndTime;
			if(strAttack_name.GetLength()==0)
			{
				strAttack_name=_T("其他");
			}
			strInsertSql.Format(_T("insert into Results_Attack_Behavior(id,attack_type,attack_code,attack_name,attack_time,mac_address,event_task_id,attack_ip) values('%s',%d,'%s','%s','%s','%s','%s','%s')"),strUid,1,strAttack_code,strAttack_name,strAttackTime,Mac,EventId,strSource_Ip);
			char* insertSql=UnicodeToUtf8(strInsertSql);
			ret = sqlite3_exec(db, insertSql, NULL, NULL, &errMsg);
			if(ret != SQLITE_OK)
			{
				OutputDebugString(_T("插入数据错误! - Results_Attack_Behavior"));
				OutputDebugString(CString(errMsg));
				sqlite3_free(errMsg);
			}
			if(insertSql != NULL)
			{
				delete []insertSql;
				insertSql = NULL;
			}
		}
	}
	if(sql != NULL)
	{
		delete []sql;
		sql = NULL;
	}
}
//获取主机层攻击
void GetHostAttack(sqlite3 *db,CString strSource_Ip, CString Mac, CString EventId)
{
	RESULTS_ATTACK_BEHAVIOR results;
	CString strsql;
	strsql.Format(_T("SELECT DISTINCT host_event_id from Safe_Log_Handle_Info where ip_address='%s'"),strSource_Ip);
	char* sql=UnicodeToUtf8(strsql);
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char ** dbResult1 = NULL;
	int nRow1, nColumn1;
	int i1, j1, index1;
	char ** dbResult2 = NULL;
	int nRow2, nColumn2;
	int i2, j2, index2;
	char ** dbResult3 = NULL;
	int nRow3, nColumn3;
	int i3, j3, index3;
	char * errMsg = NULL;
	ret = sqlite3_get_table(db, sql, &dbResult, &nRow, &nColumn, &errMsg);
	CString csFiled;
	CString strHostID;
	CString strAttackTime;
	CString strAttack_name;
	CString strEndTime,strBeginTime;
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{

				csFiled = UTF82WCS(dbResult[j]);
				if(csFiled==_T("host_event_id"))
				{
					strHostID=UTF82WCS(dbResult[index]);
					CString strMaxTime,strMinTime;

					strMaxTime.Format(_T("SELECT MAX(record_time) from Safe_Log_Handle_Info where host_event_id='%s' and ip_address='%s'"),strHostID,strSource_Ip) ;
					char * maxsql=UnicodeToUtf8(strMaxTime);
					strMinTime.Format(_T("SELECT min(record_time) from Safe_Log_Handle_Info where host_event_id='%s' and ip_address='%s'"),strHostID,strSource_Ip) ;
					char * minsql=UnicodeToUtf8(strMinTime);
					ret = sqlite3_get_table(db, maxsql, &dbResult2, &nRow2, &nColumn2, &errMsg);
					if(ret==SQLITE_OK)
					{
						index2=nColumn2;
						for (i2 = 0; i2 < nRow2; i2++)
						{
							for (j2 = 0; j2 < nColumn2; j2++)
							{																
								strEndTime=UTF82WCS(dbResult2[index2]);

								index2++;

							}
						}
					}
					if(maxsql != NULL)
					{
						delete []maxsql;
						maxsql = NULL;
					}
					ret = sqlite3_get_table(db, minsql, &dbResult3, &nRow3, &nColumn3, &errMsg);
					if(ret==SQLITE_OK)
					{
						index3=nColumn3;
						for (i3 = 0; i3 < nRow3; i3++)
						{
							for (j3 = 0; j3 < nColumn3; j3++)
							{																
								strBeginTime=UTF82WCS(dbResult3[index3]);

								index3++;

							}
						}
					}
					if(minsql != NULL)
					{
						delete []minsql;
						minsql = NULL;
					}
					CString strselectsql;

					strselectsql.Format(_T("SELECT chinese_name from Event_Contrast_Info where host_event_id='%s'"),strHostID);
					char * selectsql=UnicodeToUtf8(strselectsql);
					ret = sqlite3_get_table(db, selectsql, &dbResult1, &nRow1, &nColumn1, &errMsg);
					strAttack_name=_T("");
					if(ret==SQLITE_OK)
					{
						index1=nColumn1;
						for (i1 = 0; i1 < nRow1; i1++)
						{
							for (j1 = 0; j1 < nColumn1; j1++)
							{


								strAttack_name=UTF82WCS(dbResult1[index1]);

								index1++;

							}
						}
					}
					if(selectsql != NULL)
					{
						delete []selectsql;
						selectsql = NULL;
					}
				}
				index++;
				CString strInsertSql;
				CString strUid;
				strUid=NewGUID();
				strAttackTime=strBeginTime;
				strAttackTime+=_T("~");
				strAttackTime+=strEndTime;
				if(strAttack_name.GetLength()==0)
				{
					strAttack_name=_T("其他");
				}
				strInsertSql.Format(_T("insert into Results_Attack_Behavior(id,attack_type,attack_code,attack_name,attack_time,mac_address,event_task_id,attack_ip) values('%s',%d,'%s','%s','%s','%s','%s','%s')"),strUid,2,strHostID,strAttack_name,strAttackTime,Mac,EventId,strSource_Ip);
				char* insertSql=UnicodeToUtf8(strInsertSql);
				ret = sqlite3_exec(db, insertSql, NULL, NULL, &errMsg);
				if(ret != SQLITE_OK)
				{
					OutputDebugString(_T("插入数据错误! - Results_Attack_Behavior"));
					OutputDebugString(CString(errMsg));
					sqlite3_free(errMsg);
				}
				if(insertSql != NULL)
				{
					delete []insertSql;
					insertSql = NULL;
				}
			}
		}
	}
	if(sql != NULL)
	{
		delete []sql;
		sql = NULL;
	}
}
//分析可疑IP是否在web层面是否存在攻击、在主机层是否存在攻击、内核层是否存在攻击
void AnalysisSourceIP(CString dbPath, CString Mac, CString ip, CString EventId)
{
	char *dbName = UnicodeToUtf8(dbPath);

	sqlite3 * hSql;
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;

	ret = sqlite3_open(dbName, &hSql);
	if(ret != SQLITE_OK)
	{
		//打开失败
		OutputDebugString(_T("打开数据库失败-AttackEventJudgment"));
		if(dbName != NULL)
		{
			delete []dbName;
			dbName = NULL;
		}
		return;
	}
	CString strSelectSql,strInsertSql;
	strSelectSql.Format(_T("SELECT ip_address,attack_time_begin,attack_time_end FROM Source_Ip_Analysis"));
	char * selectsql=UnicodeToUtf8(strSelectSql);
	ret = sqlite3_get_table(hSql, selectsql, &dbResult, &nRow, &nColumn, &errMsg);
	CString csFiled;
	CString strAttack_ip;
	CString strAttack_beginTime,strAttack_EndTime;
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{

				csFiled = UTF82WCS(dbResult[j]);
				if(csFiled==_T("ip_address"))
				{
					strAttack_ip=UTF82WCS(dbResult[index]);
					GetHostAttack(hSql,strAttack_ip,Mac,EventId);
					GetWebAttack(hSql,strAttack_ip,Mac,EventId);
				}
				if(csFiled==_T("attack_time_begin"))
				{
					strAttack_beginTime=UTF82WCS(dbResult[index]);
				}
				if(csFiled==_T("attack_time_end"))
				{
					strAttack_EndTime=UTF82WCS(dbResult[index]);
				}
				index++;
			}
			CString strUid=NewGUID();
			strInsertSql.Format(_T("insert into Results_Suspicious_Ip(id,suspicious_ip,attack_time_begin,attack_time_end,mac_address,event_task_id) values('%s','%s','%s','%s','%s','%s')"),strUid,strAttack_ip,strAttack_beginTime,strAttack_EndTime,Mac,EventId);
			char* insertSql=UnicodeToUtf8(strInsertSql);
			ret = sqlite3_exec(hSql, insertSql, NULL, NULL, &errMsg);
			if(ret != SQLITE_OK)
			{
				OutputDebugString(_T("插入数据错误! - Results_Suspicious_Ip"));
				OutputDebugString(CString(errMsg));
				sqlite3_free(errMsg);
			}
			if(insertSql != NULL)
			{
				delete []insertSql;
				insertSql = NULL;
			}
		}
	}
	if(selectsql != NULL)
	{
		delete []selectsql;
		selectsql = NULL;
	}

	sqlite3_close(hSql);
}
//统计网络连接等数据
void AnalysisTable(CString dbPath, CString Mac, CString ip, CString EventId)
{
	char *dbName = UnicodeToUtf8(dbPath);

	sqlite3 * hSql;
	int ret;
	char ** dbResult = NULL;
	char * errMsg = NULL;

	ret = sqlite3_open(dbName, &hSql);
	if(ret != SQLITE_OK)
	{
		//打开失败
		OutputDebugString(_T("打开数据库失败-AttackEventJudgment"));
		if(dbName != NULL)
		{
			delete []dbName;
			dbName = NULL;
		}
		return;
	}
	sqlite3_exec(hSql,"begin;",0,0,0);

	for (vector<pair<CString,CString>>::iterator itr1 = m_vecWindosStatistics.begin();itr1 != m_vecWindosStatistics.end();++itr1)
	{
		CString strTableName=itr1->first;
		CString strCount;
		CString strUid=NewGUID();
		int nCount=GetTableCount1(hSql,UnicodeToUtf8(strTableName));
		strCount.Format(_T("%d"),nCount);
		CString stranalysis_config_id = itr1->second;
		CString cSql;
		cSql.Format(_T("insert into Data_Analysis_Detail(analysis_detail_id,event_task_id,analysis_config_id,attack_value,mac_address) values('%s','%s','%s','%s','%s')"),strUid,EventId,stranalysis_config_id,strCount,Mac);
		char* insertSql=UnicodeToUtf8(cSql);
		ret = sqlite3_exec(hSql, insertSql, NULL, NULL, &errMsg);
		if(ret != SQLITE_OK)
		{
			OutputDebugString(_T("插入数据错误! - Data_Analysis_Detail"));
			OutputDebugString(CString(errMsg));
			sqlite3_free(errMsg);
		}
		if(insertSql != NULL)
		{
			delete []insertSql;
			insertSql = NULL;
		}

	}
	for (vector<pair<CString,CString>>::iterator itr2 = m_vecAttackType.begin();itr2 != m_vecAttackType.end();++itr2)
	{
		CString strCode=itr2->first;
		int nCount=GetWebAttackCount(hSql,UnicodeToUtf8(strCode));
		CString strCount;
		CString strUid=NewGUID();
		strCount.Format(_T("%d"),nCount);
		CString stranalysis_config_id = itr2->second;
		CString cSql;
		cSql.Format(_T("insert into Data_Analysis_Detail(analysis_detail_id,event_task_id,analysis_config_id,attack_value,mac_address) values('%s','%s','%s','%s','%s')"),strUid,EventId,stranalysis_config_id,strCount,Mac);
		char* insertSql=UnicodeToUtf8(cSql);
		ret = sqlite3_exec(hSql, insertSql, NULL, NULL, &errMsg);
		if(ret != SQLITE_OK)
		{
			OutputDebugString(_T("插入数据错误! - Data_Analysis_Detail"));
			OutputDebugString(CString(errMsg));
			sqlite3_free(errMsg);
		}
		if(insertSql != NULL)
		{
			delete []insertSql;
			insertSql = NULL;
		}

	}
	sqlite3_exec(hSql,"commit;",0,0,0);
	sqlite3_close(hSql);

}
// 事件性质判定及入库
void AttackEventJudgment(CString dbPath, CString Mac, CString ip, CString EventId)
{
	char *dbName = UnicodeToUtf8(dbPath);

	sqlite3 * hSql;
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;

	ret = sqlite3_open(dbName, &hSql);
	if(ret != SQLITE_OK)
	{
		//打开失败
		OutputDebugString(_T("打开数据库失败-AttackEventJudgment"));
		if(dbName != NULL)
		{
			delete []dbName;
			dbName = NULL;
		}
		return;
	}
	sqlite3_exec(hSql,"begin;",0,0,0);
	char *cIp = UnicodeToUtf8(ip);
	char *cMac = UnicodeToUtf8(Mac);
	char *cEventId = UnicodeToUtf8(EventId);

	// 混合攻击判断时需要
	BOOL bIsCVI = FALSE;
	BOOL bIsWBPI = FALSE;
	BOOL bIsBDAI = FALSE;

	char sql[1024];

	// CVI：计算机病毒事件
	int nCVI = 0;
	nCVI = GetTableCount1(hSql, "Virus_Data");
	if(nCVI > 0)
	{
		bIsCVI = TRUE;
		CString temp = _T("计算机病毒事件");
		char *cTemp = UnicodeToUtf8(temp);
		CString temp1 = _T("存在病毒文件");
		char *cTemp1 = UnicodeToUtf8(temp1);
		InsertEventJudgment(hSql, cMac, cIp, cEventId, cTemp, cTemp1);
		delete []cTemp;
		delete []cTemp1;
	}

	//WBPI：网页内嵌恶意代码事件
	int nWBPI = 0;
	// 判断webshell文件里是否包含有图片类型, jpg, png, gif, bmp
	CString CsBasis = _T("");
	// 文件中的webshell
	int nCount1 = 0;
	if(IsWebshellIncludePhoto(hSql, &nCount1))
		CsBasis = _T("webshell文件里包含图片类型");
	nWBPI += nCount1;
	const char *sql2 = "select count(*) from Web_Attack_Action where attack_code = 'java_ouin_stream'";
	int nCount2 = GetTableCount2(hSql, sql2);
	if(nCount2 > 0)
	{
		nWBPI += nCount2;
		if(CsBasis.IsEmpty())
			CsBasis = _T("java反序列化攻击");
		else
			CsBasis += _T(",java反序列化攻击");
	}
	const char *sql3 = "select count(*) from Web_Attack_Action where attack_code = 'shell_shock'";
	int nCount3 = GetTableCount2(hSql, sql3);
	if(nCount3 > 0)
	{
		nWBPI += nCount3;
		if(CsBasis.IsEmpty())
			CsBasis = _T("shellshock破壳攻击");
		else
			CsBasis += _T(",shellshock破壳攻击");
	}
	const char *sqlanlian = "select count(*) from Other_Action where type = '4'";
	int nanliancount = GetTableCount2(hSql, sqlanlian);
	if(nanliancount > 0)
	{
		nWBPI += nanliancount;
		if(CsBasis.IsEmpty())
			CsBasis = _T("暗链检测");
		else
			CsBasis += _T(",暗链检测");
	}
	if(!CsBasis.IsEmpty())
	{
		bIsWBPI = TRUE;
		char *temp = UnicodeToUtf8(CsBasis);
		CString temp1 = _T("网页内嵌恶意代码事件");
		char *cTemp1 = UnicodeToUtf8(temp1);
		InsertEventJudgment(hSql, cMac, cIp, cEventId, cTemp1, temp);
		delete []temp;
		delete []cTemp1;
	}
	CsBasis.Empty();

	//BDAI：后门攻击事件
	int nBDAI = 0;
	const char *sql4 = "select count(*) from Other_Action where type = '1'";
	int nCount4 = GetTableCount2(hSql, sql4);
	if(nCount4 > 0)
	{
		nBDAI += nCount4;
		CsBasis = _T("含有Webshell");
	}
	const char *sql41 = "select count(*) from Other_Action where type = '2'";
	int nCount5 = GetTableCount2(hSql, sql41);
	if(nCount5 > 0)
	{
		nBDAI += nCount5;
		if(CsBasis.IsEmpty())
			CsBasis = _T("含有APT");
		else
			CsBasis += _T("、APT");
	}
	const char *lessfileattack="select count(*) from file_less_attack";
	int cLessCount=GetTableCount2(hSql,lessfileattack);
	if(cLessCount > 0)
	{
		nBDAI += cLessCount;
		if(CsBasis.IsEmpty())
			CsBasis = _T("无文件攻击");
		else
			CsBasis += _T("、无文件攻击");
	}
	const char *whiteandblackattack="select count(*) from whiteandblack_attack";
	int whiteandblackCount=GetTableCount2(hSql,whiteandblackattack);
	if(whiteandblackCount > 0)
	{
		nBDAI += whiteandblackCount;
		if(CsBasis.IsEmpty())
			CsBasis = _T("白加黑攻击");
			
		else
			CsBasis += _T("、白加黑攻击");
	}
	if(!CsBasis.IsEmpty())
	{
		bIsBDAI = TRUE;
		char *temp = UnicodeToUtf8(CsBasis);
		CString temp1 = _T("后门攻击事件");
		char *cTemp1 = UnicodeToUtf8(temp1);
		InsertEventJudgment(hSql, cMac, cIp, cEventId, cTemp1, temp);
		delete []temp;
		delete []cTemp1;
	}

	CsBasis.Empty();

	// VAI：漏洞攻击事件
	int nVAI = 0;
	const char *sql5 = "select count(*) from Web_Attack_Action where attack_code = 'sql_injection'";
	int nCount6 = GetTableCount2(hSql, sql5);
	if(nCount6 > 0)
	{
		nVAI += nCount6;
		CsBasis = _T("sql注入");
	}
	const char *sql6 = "select count(*) from Web_Attack_Action where attack_code = 'xss'";
	int nCount7 = GetTableCount2(hSql, sql6);
	if(nCount7 > 0)
	{
		nVAI += nCount7;
		if(CsBasis.IsEmpty())
			CsBasis = _T("xss攻击");
		else
			CsBasis += _T(",xss攻击");
	}
	const char *sql7 = "select count(*) from Web_Attack_Action where attack_code = 'file_include'";
	int nCount8 = GetTableCount2(hSql, sql7);
	if(nCount8 > 0)
	{
		nVAI += nCount8;
		if(CsBasis.IsEmpty())
			CsBasis = _T("任意文件读取");
		else
			CsBasis += _T(",任意文件读取");
	}
	const char *sql71 = "select count(*) from Web_Attack_Action where attack_code = 'struts2'";
	int nCount9 = GetTableCount2(hSql, sql71);
	if(nCount9 > 0)
	{
		nVAI += nCount9;
		if(CsBasis.IsEmpty())
			CsBasis = _T("Struts2远程命令执行");
		else
			CsBasis += _T(",Struts2远程命令执行");
	}
	const char *lessfilesql = "select count(*) from file_less_attack";
	int nCountless = GetTableCount2(hSql, lessfilesql);
	if(nCountless > 0)
	{
		nVAI += nCountless;
		if(CsBasis.IsEmpty())
			CsBasis = _T("无文件攻击");
		else
			CsBasis += _T(",无文件攻击");
	}
	const char *sql72 = "select count(*) from Web_Attack_Action where attack_code = 'java_ouin_stream'";
	int nCount10 = GetTableCount2(hSql, sql72);
	if(nCount10 > 0)
	{
		nVAI += nCount10;
		if(CsBasis.IsEmpty())
			CsBasis = _T("java反序列化攻击");
		else
			CsBasis += _T(",java反序列化攻击");
	}

	const char *sql73 = "select count(*) from Web_Attack_Action where attack_code = 'shell_shock'";
	int nCount11 = GetTableCount2(hSql, sql73);
	if(nCount11 > 0)
	{
		nVAI += nCount11;
		if(CsBasis.IsEmpty())
			CsBasis = _T("shellshock破壳攻击");
		else
			CsBasis += _T(",shellshock破壳攻击");
	}

	const char *sql74 = "select count(*) from Web_Attack_Action where attack_code = 'http_crlf'";
	int nCount12 = GetTableCount2(hSql, sql74);
	if(nCount12 > 0)
	{
		nVAI += nCount12;
		if(CsBasis.IsEmpty())
			CsBasis = _T("CRLF HTTP协议头操纵");
		else
			CsBasis += _T(",CRLF HTTP协议头操纵");
	}
	const char *sql75 = "select count(*) from Web_Attack_Action where attack_code = 'struts2_attack'";
	int nCountstruts2_attack = GetTableCount2(hSql, sql75);
	if(nCountstruts2_attack > 0)
	{
		nVAI += nCountstruts2_attack;
		if(CsBasis.IsEmpty())
			CsBasis = _T("Struts2攻击威胁检测");
		else
			CsBasis += _T(",Struts2攻击威胁检测");
	}
	const char *sql76 = "select count(*) from Web_Attack_Action where attack_code = 'struts2_remote_command_exe'";
	int nCountstruts2_remote_command_exe = GetTableCount2(hSql, sql76);
	if(nCountstruts2_remote_command_exe > 0)
	{
		nVAI += nCountstruts2_remote_command_exe;
		if(CsBasis.IsEmpty())
			CsBasis = _T("Struts2远程命令执行");
		else
			CsBasis += _T(",Struts2远程命令执行");
	}
	//11.2
	const char *sqlcommand = "select count(*) from Web_Attack_Action where attack_code = 'command_execution'";
	int nCommandexecution = GetTableCount2(hSql, sqlcommand);
	if(nCommandexecution > 0)
	{
		nVAI += nCommandexecution;
		if(CsBasis.IsEmpty())
			CsBasis = _T("命令执行");
		else
			CsBasis += _T(",命令执行");
	}
	if(!CsBasis.IsEmpty())
	{
		char *temp = UnicodeToUtf8(CsBasis);
		CString temp1 = _T("漏洞攻击事件");
		char *cTemp1 = UnicodeToUtf8(temp1);
		
		InsertEventJudgment(hSql, cMac, cIp, cEventId, cTemp1, temp);
		delete []temp;
		delete []cTemp1;
	}

	// NSEI：网络扫描窃听事件
	int nNSEI = 0;
	const char *sql9 = "select count(*) from Web_Attack_Action where attack_code = 'scan_robots'";
	int nCount13 = GetTableCount2(hSql, sql9);
	if(nCount13 > 0)
	{
		nNSEI += nCount13;

		CString temp = _T("网络扫描窃听事件");
		char *cTemp = UnicodeToUtf8(temp);
		CString temp1 = _T("扫描入侵");
		char *cTemp1 = UnicodeToUtf8(temp1);
		InsertEventJudgment(hSql, cMac, cIp, cEventId, cTemp, cTemp1);
		delete []cTemp;
		delete []cTemp1;
	}
	// IMI：信息假冒事件
	CsBasis.Empty();
	int nIMI = 0;
	const char *sql10 = "select count(*) from Web_Attack_Action where attack_code = 'urljump'";
	int nCount14 = GetTableCount2(hSql, sql10);
	if(nCount14>0)
	{
		nIMI +=nCount14;
		if(CsBasis.IsEmpty())
			CsBasis = _T("域名跳转");

		else
			CsBasis += _T(",域名跳转");
	}
	const char *whiteandblackattack1="select count(*) from whiteandblack_attack";
	int whiteandblackCount1=GetTableCount2(hSql,whiteandblackattack1);
	if(whiteandblackCount1>0)
	{
		nIMI +=whiteandblackCount1;
		if(CsBasis.IsEmpty())
			CsBasis = _T("白加黑攻击");


		else
			CsBasis += _T(",白加黑攻击");
	}
	if(!CsBasis.IsEmpty())
	{
		char *temp = UnicodeToUtf8(CsBasis);
		CString temp1 = _T("信息假冒事件");

		char *cTemp1 = UnicodeToUtf8(temp1);

		InsertEventJudgment(hSql, cMac, cIp, cEventId, cTemp1, temp);
		delete []temp;
		delete []cTemp1;
	}
	
	//  ILEI：信息泄漏事件
	int nILEI = 0;
	CsBasis.Empty();
	const char *sql11 = "select count(*) from Web_Attack_Action where attack_code = 'sensitive_file'";
	int nCount15 = GetTableCount2(hSql, sql11);
	if(nCount15 > 0)
	{
		nILEI += nCount15;

		CString temp = _T("信息泄漏事件");
		char *cTemp = UnicodeToUtf8(temp);
		CString temp1 = _T("敏感文件访问");
		char *cTemp1 = UnicodeToUtf8(temp1);
		InsertEventJudgment(hSql, cMac, cIp, cEventId, cTemp, cTemp1);
		delete []cTemp;
		delete []cTemp1;
	}
	//疑似信息窃取事件
	CsBasis.Empty();
	int nSuspected_III=0;
	int nSuspected_IIICount=0;
	const char *getSusFilesql="SELECT COUNT(*) from Suspicious_File where file_type='evtx'or file_type='php' or file_type='sql' or file_type='exe'or file_type='bak'or file_type='db' or file_type='log' or file_type='config'";
	nSuspected_III=GetTableCount2(hSql,getSusFilesql);
	if(nSuspected_III>0)
	{
		nSuspected_IIICount +=nSuspected_III;
		if(CsBasis.IsEmpty())
			CsBasis = _T("磁盘可疑文件操作");

		else
			CsBasis += _T(",磁盘可疑文件操作");
	}
	const char *getSusFilesqlbyusn="SELECT COUNT(*) from usn_file where usnfile_type='evtx'or usnfile_type='php' or usnfile_type='sql' or usnfile_type='exe'or usnfile_type='bak'or usnfile_type='db' or usnfile_type='log' or usnfile_type='config'";
	nSuspected_III=0;
	nSuspected_III=GetTableCount2(hSql,getSusFilesqlbyusn);
	if(nSuspected_III>0)
	{
		nSuspected_IIICount +=nSuspected_III;
		if(CsBasis.IsEmpty())
			CsBasis = _T("USN可疑文件操作");


		else
			CsBasis += _T(",USN可疑文件操作");
	}
	const char *getFile_Operationsql="SELECT COUNT(*) from File_Operation_Light where file_type='evtx'or file_type='php' or file_type='sql' or file_type='exe'or file_type='bak'or file_type='db' or file_type='log' or file_type='config'";
	nSuspected_III=0;
	nSuspected_III=GetTableCount2(hSql,getFile_Operationsql);
	if(nSuspected_III>0)
	{
		nSuspected_IIICount +=nSuspected_III;
		if(CsBasis.IsEmpty())
			CsBasis = _T("异常文件操作");



		else
			CsBasis += _T(",异常文件操作");

	}
	if(!CsBasis.IsEmpty())
	{
		char *temp = UnicodeToUtf8(CsBasis);
		CString temp1 = _T("疑似信息窃取事件");

		char *cTemp1 = UnicodeToUtf8(temp1);

		InsertEventJudgment(hSql, cMac, cIp, cEventId, cTemp1, temp);
		delete []temp;
		delete []cTemp1;
	}
	//其他事件
	CsBasis.Empty();
	int nOtherevent=0;
	int nOthereventCount=0;
	//其他事件不包含日志清除
	const char *getOthereventsqlbylog="SELECT COUNT(*) from Safe_Log_Handle_Info where is_no_abnormal='1' and host_event_id !='1102'";
	nOtherevent=GetTableCount2(hSql,getOthereventsqlbylog);
	if(nOtherevent>0)
	{
		nOthereventCount +=nOtherevent;
		if(CsBasis.IsEmpty())
			CsBasis = _T("异常主机日志(其他)");
			
		else
			CsBasis += _T(",异常主机日志(其他)");

	}
	nOtherevent=0;
	const char *getOthereventsql="SELECT COUNT(*) from Safe_Log_Handle_Info where  host_event_id =‘1102'";
	nOtherevent=GetTableCount2(hSql,getOthereventsql);
	if(nOtherevent>0)
	{
		nOthereventCount +=nOtherevent;
		if(CsBasis.IsEmpty())
			CsBasis = _T("异常日志(清除日志)");
		
		else
			CsBasis += _T(",异常日志(清除日志)");

	}
	nOtherevent=0;
	CString strgetOthersql;
	CString strUserName;
	const char * getUserName="SELECT account_name from Suspicious_Account";

	ret = sqlite3_get_table(hSql, getUserName, &dbResult, &nRow, &nColumn, &errMsg);
	int count=0;
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				strUserName = UTF82WCS(dbResult[index]);
				strgetOthersql.Format(_T("SELECT COUNT(*) from host_command where usrname ='%s'"),strUserName);

				char *getOthereventsql1=UnicodeToUtf8(strgetOthersql);
				nOtherevent=0;
				nOtherevent=GetTableCount2(hSql,getOthereventsql1);
				if(nOtherevent>0)
				{
					
					nOthereventCount +=nOtherevent;
					if(count==0)
					{

					if(CsBasis.IsEmpty())
						CsBasis = _T("主机命令执行(可疑账户)");

					else
						CsBasis += _T(",主机命令执行(可疑账户)");
					}
					count++;

				}
				index++;
			}
		}
		sqlite3_free_table(dbResult);	// 释放结果
	}
	if(errMsg!=NULL)
	sqlite3_free(errMsg);
	
	if(!CsBasis.IsEmpty())
	{
		char *temp = UnicodeToUtf8(CsBasis);
		CString temp1 = _T("其他事件（敏感行为）");


		char *cTemp1 = UnicodeToUtf8(temp1);

		InsertEventJudgment(hSql, cMac, cIp, cEventId, cTemp1, temp);
		delete []temp;
		delete []cTemp1;
	}
	//其他事件
	//  III：信息窃取事件
	int nIII = 0;

	// BAI：混合攻击程序事件(含有计算机病毒事件、网页内嵌恶意代码事件和后门攻击事件)
	int nBAI = 0;
	if(bIsCVI && bIsWBPI && bIsBDAI)
	{
		nBAI = 1;
		CString temp = _T("混合攻击程序事件");
		char *cTemp = UnicodeToUtf8(temp);
		CString temp1 = _T("含有计算机病毒事件、网页内嵌恶意代码事件和后门攻击事件");
		char *cTemp1 = UnicodeToUtf8(temp1);
		InsertEventJudgment(hSql, cMac, cIp, cEventId, cTemp, cTemp1);
		delete []cTemp;
		delete []cTemp1;
	}

	// 攻击事件统计
	memset(sql, 0, sizeof(sql));
	char *uuid2 = UnicodeToUtf8(NewGUID());
	_snprintf_s(sql, 1024, "insert into Attack_Event_Statistics(id, CVI, WBPI, BDAI, VAI, NSEI, IMI, ILEI, III, BAI,Suspected_III, other_event,mac_address, event_task_id) values('%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d','%d','%d', '%s', '%s')", 
		uuid2, nCVI, nWBPI, nBDAI, nVAI, nNSEI, nIMI, nILEI, nIII, nBAI,nSuspected_IIICount,nOthereventCount, cMac, cEventId);
	ret = sqlite3_exec(hSql, sql, NULL, NULL, &errMsg);
	if(ret != SQLITE_OK)
	{
		OutputDebugString(_T("插入数据错误! - Attack_Event_Statistics"));
		OutputDebugString(CString(errMsg));
		sqlite3_free(errMsg);
	}
	if(uuid2 != NULL)
	{
		delete []uuid2;
		uuid2 = NULL;
	}
	
	// 事件类型统计
	int nHarmful_application = nCVI + nWBPI + nBAI;		// 有害程序事件
	int nNetwork_attack = nBDAI + nVAI + nNSEI;			// 网络攻击事件
	int nInfo_destroy = nIMI + nILEI + nIII;			// 信息破坏事件

	memset(sql, 0, sizeof(sql));
	char *uuid3 = UnicodeToUtf8(NewGUID());
	_snprintf_s(sql, 1024, "insert into Event_Type_Statistics(id, harmful_application, network_attack, info_destroy, mac_address, event_task_id) values('%s', '%d', '%d', '%d', '%s', '%s')", 
		uuid3, nHarmful_application, nNetwork_attack, nInfo_destroy, cMac, cEventId);
	ret = sqlite3_exec(hSql, sql, NULL, NULL, &errMsg);
	if(ret != SQLITE_OK)
	{
		OutputDebugString(_T("插入数据错误! - Event_Type_Statistics"));
		OutputDebugString(CString(errMsg));
		sqlite3_free(errMsg);
	}
	if(uuid3 != NULL)
	{
		delete []uuid3;
		uuid3 = NULL;
	}
	sqlite3_exec(hSql,"commit;",0,0,0);
	sqlite3_close(hSql);
	if(cIp != NULL)
	{
		delete []cIp;
		cIp = NULL;
	}
	if(cMac != NULL)
	{
		delete []cMac;
		cMac = NULL;
	}
	if(cEventId != NULL)
	{
		delete []cEventId;
		cEventId = NULL;
	}

	return;
}

void InitVector()
{
	vtAccountLogin.clear();	
	vtAccountManage.clear();	
	vtDetailedTrace.clear();	
	vtDSAccess.clear();		
	vtLoginLogout.clear();	
	vtObjectAccess.clear();	
	vtPolicyChange.clear();	
	vtPrivilegeUse.clear();	
	vtSystem.clear();			
	//vector<pair<CString, CString>>vtAccountLogin;	// 账户登录
	pair<CString, CString> pr1(_T("审核凭据验证"), _T("未配置"));
	vtAccountLogin.push_back(pr1);
	pair<CString, CString> pr2(_T("审核 Kerberos 身份验证服务"), _T("未配置"));
	vtAccountLogin.push_back(pr2);
	pair<CString, CString> pr3(_T("审核 Kerberos 服务票证操作"), _T("未配置"));
	vtAccountLogin.push_back(pr3);
	pair<CString, CString> pr4(_T("审核其他帐户登录事件"), _T("未配置"));
	vtAccountLogin.push_back(pr4);
	//vector<pair<CString, CString>>vtAccountManage;	// 账户管理
	pair<CString, CString> pr5(_T("审核应用程序组管理"), _T("未配置"));
	vtAccountManage.push_back(pr5);
	pair<CString, CString> pr6(_T("审核计算机帐户管理"), _T("未配置"));
	vtAccountManage.push_back(pr6);
	pair<CString, CString> pr7(_T("审核通讯组管理"), _T("未配置"));
	vtAccountManage.push_back(pr7);
	pair<CString, CString> pr8(_T("审核其他帐户管理事件"), _T("未配置"));
	vtAccountManage.push_back(pr8);
	pair<CString, CString> pr9(_T("审核安全组管理"), _T("未配置"));
	vtAccountManage.push_back(pr9);
	pair<CString, CString> pr10(_T("审核用户帐户管理"), _T("未配置"));
	vtAccountManage.push_back(pr10);
	//vector<pair<CString, CString>>vtDetailedTrace;	// 详细跟踪
	pair<CString, CString> pr11(_T("审核 DPAPI 活动"), _T("未配置"));
	vtDetailedTrace.push_back(pr11);
	pair<CString, CString> pr12(_T("审核 PNP 活动"), _T("未配置"));
	vtDetailedTrace.push_back(pr12);
	pair<CString, CString> pr13(_T("审核进程创建"), _T("未配置"));
	vtDetailedTrace.push_back(pr13);
	pair<CString, CString> pr14(_T("审核进程终止"), _T("未配置"));
	vtDetailedTrace.push_back(pr14);
	pair<CString, CString> pr15(_T("审核 RPC 事件"), _T("未配置"));
	vtDetailedTrace.push_back(pr15);
	pair<CString, CString> pr16(_T("审核令牌权限已调整"), _T("未配置"));
	vtDetailedTrace.push_back(pr16);
	//vector<pair<CString, CString>>vtDSAccess;		// DS访问
	pair<CString, CString> pr17(_T("审核详细的目录服务复制"), _T("未配置"));
	vtDSAccess.push_back(pr17);
	pair<CString, CString> pr18(_T("审核目录服务访问"), _T("未配置"));
	vtDSAccess.push_back(pr18);
	pair<CString, CString> pr19(_T("审核目录服务更改"), _T("未配置"));
	vtDSAccess.push_back(pr19);
	pair<CString, CString> pr20(_T("审核目录服务复制"), _T("未配置"));
	vtDSAccess.push_back(pr20);
	//vector<pair<CString, CString>>vtLoginLogout;	// 登录/注销
	pair<CString, CString> pr21(_T("审核帐户锁定"), _T("未配置"));
	vtLoginLogout.push_back(pr21);
	pair<CString, CString> pr22(_T("审核用户/设备声明"), _T("未配置"));
	vtLoginLogout.push_back(pr22);
	pair<CString, CString> pr23(_T("审核组成员身份"), _T("未配置"));
	vtLoginLogout.push_back(pr23);
	pair<CString, CString> pr24(_T("审核 IPsec 扩展模式"), _T("未配置"));
	vtLoginLogout.push_back(pr24);
	pair<CString, CString> pr25(_T("审核 IPsec 主模式"), _T("未配置"));
	vtLoginLogout.push_back(pr25);
	pair<CString, CString> pr26(_T("审核 IPsec 快速模式"), _T("未配置"));
	vtLoginLogout.push_back(pr26);
	pair<CString, CString> pr27(_T("审核注销"), _T("未配置"));
	vtLoginLogout.push_back(pr27);
	pair<CString, CString> pr28(_T("审核登录"), _T("未配置"));
	vtLoginLogout.push_back(pr28);
	pair<CString, CString> pr29(_T("审核网络策略服务器"), _T("未配置"));
	vtLoginLogout.push_back(pr29);
	pair<CString, CString> pr30(_T("审核其他登录/注销事件"), _T("未配置"));
	vtLoginLogout.push_back(pr30);
	pair<CString, CString> pr31(_T("审核特殊登录"), _T("未配置"));
	vtLoginLogout.push_back(pr31);
	//vector<pair<CString, CString>>vtObjectAccess;	// 对象访问
	pair<CString, CString> pr32(_T("审核已生成应用程序"), _T("未配置"));
	vtObjectAccess.push_back(pr32);
	pair<CString, CString> pr33(_T("审核证书服务"), _T("未配置"));
	vtObjectAccess.push_back(pr33);
	pair<CString, CString> pr34(_T("审核详细的文件共享"), _T("未配置"));
	vtObjectAccess.push_back(pr34);
	pair<CString, CString> pr35(_T("审核文件共享"), _T("未配置"));
	vtObjectAccess.push_back(pr35);
	pair<CString, CString> pr36(_T("审核文件系统"), _T("未配置"));
	vtObjectAccess.push_back(pr36);
	pair<CString, CString> pr37(_T("审核筛选平台连接"), _T("未配置"));
	vtObjectAccess.push_back(pr37);
	pair<CString, CString> pr38(_T("审核筛选平台数据包丢弃"), _T("未配置"));
	vtObjectAccess.push_back(pr38);
	pair<CString, CString> pr39(_T("审核句柄操作"), _T("未配置"));
	vtObjectAccess.push_back(pr39);
	pair<CString, CString> pr40(_T("审核内核对象"), _T("未配置"));
	vtObjectAccess.push_back(pr40);
	pair<CString, CString> pr41(_T("审核其他对象访问事件"), _T("未配置"));
	vtObjectAccess.push_back(pr41);
	pair<CString, CString> pr42(_T("审核注册表"), _T("未配置"));
	vtObjectAccess.push_back(pr42);
	pair<CString, CString> pr43(_T("审核可移动存储"), _T("未配置"));
	vtObjectAccess.push_back(pr43);
	pair<CString, CString> pr44(_T("审核 SAM"), _T("未配置"));
	vtObjectAccess.push_back(pr44);
	pair<CString, CString> pr45(_T("审核中心访问策略暂存"), _T("未配置"));
	vtObjectAccess.push_back(pr45);
	//vector<pair<CString, CString>>vtPolicyChange;	// 策略更改
	pair<CString, CString> pr46(_T("审核审核策略更改"), _T("未配置"));
	vtPolicyChange.push_back(pr46);
	pair<CString, CString> pr47(_T("审核身份验证策略更改"), _T("未配置"));
	vtPolicyChange.push_back(pr47);
	pair<CString, CString> pr48(_T("审核授权策略更改"), _T("未配置"));
	vtPolicyChange.push_back(pr48);
	pair<CString, CString> pr49(_T("审核筛选平台策略更改"), _T("未配置"));
	vtPolicyChange.push_back(pr49);
	pair<CString, CString> pr50(_T("审核 MPSSVC 规则级别策略更改"), _T("未配置"));
	vtPolicyChange.push_back(pr50);
	pair<CString, CString> pr51(_T("审核其他策略更改事件"), _T("未配置"));
	vtPolicyChange.push_back(pr51);
	//vector<pair<CString, CString>>vtPrivilegeUse;	// 特权使用
	pair<CString, CString> pr52(_T("审核非敏感权限使用"), _T("未配置"));
	vtPrivilegeUse.push_back(pr52);
	pair<CString, CString> pr53(_T("审核其他权限使用事件"), _T("未配置"));
	vtPrivilegeUse.push_back(pr53);
	pair<CString, CString> pr54(_T("审核敏感权限使用"), _T("未配置"));
	vtPrivilegeUse.push_back(pr54);
	//vector<pair<CString, CString>>vtSystem;			// 系统
	pair<CString, CString> pr55(_T("审核 IPsec 驱动程序"), _T("未配置"));
	vtSystem.push_back(pr55);
	pair<CString, CString> pr56(_T("审核其他系统事件"), _T("未配置"));
	vtSystem.push_back(pr56);
	pair<CString, CString> pr57(_T("审核安全状态更改"), _T("未配置"));
	vtSystem.push_back(pr57);
	pair<CString, CString> pr58(_T("审核安全系统扩展"), _T("未配置"));
	vtSystem.push_back(pr58);
	pair<CString, CString> pr59(_T("审核系统完整性"), _T("未配置"));
	vtSystem.push_back(pr59);
}

void GetSetting(CString Subcategory, CString InclusionSetting)
{
	vector<pair<CString, CString>>::iterator it;
	for(it = vtAccountLogin.begin(); it != vtAccountLogin.end(); it++)
	{
		if(Subcategory == it->first)
		{
			it->second = InclusionSetting;
			return;
		}
	}
	for(it = vtAccountManage.begin(); it != vtAccountManage.end(); it++)
	{
		//Subcategory = _T("审核用户账户管理");
		if(Subcategory == it->first)
		{
			it->second = InclusionSetting;
			return;
		}
	}
	for(it = vtDetailedTrace.begin(); it != vtDetailedTrace.end(); it++)
	{
		if(Subcategory == it->first)
		{
			it->second = InclusionSetting;
			return;
		}
	}
	for(it = vtDSAccess.begin(); it != vtDSAccess.end(); it++)
	{
		if(Subcategory == it->first)
		{
			it->second = InclusionSetting;
			return;
		}
	}
	for(it = vtLoginLogout.begin(); it != vtLoginLogout.end(); it++)
	{
		if(Subcategory == it->first)
		{
			it->second = InclusionSetting;
			return;
		}
	}
	for(it = vtObjectAccess.begin(); it != vtObjectAccess.end(); it++)
	{
		if(Subcategory == it->first)
		{
			it->second = InclusionSetting;
			return;
		}
	}
	for(it = vtPolicyChange.begin(); it != vtPolicyChange.end(); it++)
	{
		if(Subcategory == it->first)
		{
			it->second = InclusionSetting;
			return;
		}
	}
	for(it = vtPrivilegeUse.begin(); it != vtPrivilegeUse.end(); it++)
	{
		if(Subcategory == it->first)
		{
			it->second = InclusionSetting;
			return;
		}
	}
	for(it = vtSystem.begin(); it != vtSystem.end(); it++)
	{
		if(Subcategory == it->first)
		{
			it->second = InclusionSetting;
			return;
		}
	}

}

// 获取高级策略审核
void GetSeniorPolicyAudit()
{
	InitVector();
	TCHAR path[MAX_PATH];
	memset(path, 0, sizeof(TCHAR)*MAX_PATH);
	GetSystemDirectory(path, MAX_PATH);

	// 32位程序在64位操作系统中,所有对System32路径下的操作都会重定向到SysWOW64里


	//if (Wow64EnableWow64FsRedirection(FALSE))//关闭重定向
	if (myWow64EnableWow64FsRedirection(FALSE))//关闭重定向
	{
		CString file;
		file.Format(_T("%s\\GroupPolicy\\Machine\\Microsoft\\Windows NT\\Audit\\audit.csv"), path);
		if(IsFileExist(file))
		{
			char *cFileName = UnicodeToANSI(file);
			std::ifstream inFile(cFileName, std::ios::in);
			if (!inFile)
			{
				int l=0;
			}
			std::string line;
			int i=0;
			while (getline(inFile, line))   //整行读取，换行符“\n”区分，遇到文件尾标志eof终止读取
			{

				std::istringstream sin(line); //将整行字符串line读入到字符串流istringstream中
				std::vector<std::string> fields; //声明一个字符串向量
				std::string field;
				while (getline(sin, field, ',')) //将字符串流sin中的字符读入到field字符串中，以逗号为分隔符
				{
					fields.push_back(field); //将刚刚读取的字符串添加到向量fields中
				}
				if(i!=0)
				{			
					CString Subcategory= UTF82WCS((fields[2]).c_str());
					CString InclusionSetting= UTF82WCS((fields[4]).c_str());
					GetSetting(Subcategory, InclusionSetting);
				}
				i++; 
			}
			inFile.close();
			if(cFileName != NULL)
			{
				delete []cFileName;
				cFileName = NULL;
			}
		}
		else
		{
			OutputDebugString(_T("audit.csv文件不存在!"));
		}
		//Wow64EnableWow64FsRedirection(TRUE);//恢复重定向
		myWow64EnableWow64FsRedirection(TRUE);//恢复重定向
	}

}

// 释放空间 delete[]
void DeleteChar(char *p)
{
	if(p != NULL)
	{
		delete []p;
		p = NULL;
	}
}
void getFileMd5(CString lpfile,sqlite3 *db)
{

	CFileFind finder;
	BOOL bl=finder.FindFile(lpfile);// 当前目录
	while(bl)
	{
		bl=finder.FindNextFile();
		if(finder.IsDots())// 当前目录和上级目录
		{
		}
		else if(finder.IsDirectory())// 子目录
		{
			CString cstemp;
			cstemp.Format(_T("%s"),finder.GetFilePath());
			cstemp+=_T("\\*.*");
			getFileMd5(cstemp,db);
		}
		else
		{
			if (myWow64EnableWow64FsRedirection(FALSE))//关闭重定向
			{
				CString strfilename=finder.GetFilePath();// 文件
				OutputDebugString(strfilename);
				OutputDebugString(CTOOLBOX4App::ms_strMacAddr);
				//OutputDebugString(m_csEventTaskId);
				WIN32_FIND_DATA* findData = new WIN32_FIND_DATA;
				memset(findData,0,sizeof(WIN32_FIND_DATA));
				HANDLE hd=FindFirstFile(strfilename,findData);
				SYSTEMTIME CreationTime;
				FILETIME ftTempCreationTime;
				SYSTEMTIME LastAccessTime;
				FILETIME ftTempLastAccessTime;
				SYSTEMTIME LastWriteTime;
				FILETIME ftTempLastWriteTime;
				CString strCreationTime;//创建时间
				CString strLastAccessTime;//访问时间
				CString strLastWriteTime;//修改时间
				DWORDLONG FileSize = (findData->nFileSizeHigh * (MAXDWORD+1)) + findData->nFileSizeLow;
				CString strFileSize;
				strFileSize.Format(_T("%I64d"),FileSize);
				FileTimeToLocalFileTime(&(findData->ftCreationTime),&ftTempCreationTime);
				FileTimeToSystemTime(&ftTempCreationTime, &CreationTime);
				strCreationTime.Format(TEXT("%04d-%02d-%02d %02d:%02d:%02d"), CreationTime.wYear
					, CreationTime.wMonth, CreationTime.wDay, CreationTime.wHour, CreationTime.wMinute
					, CreationTime.wSecond);
				FileTimeToLocalFileTime(&(findData->ftLastAccessTime),&ftTempLastAccessTime);
				FileTimeToSystemTime(&ftTempLastAccessTime, &LastAccessTime);
				strLastAccessTime.Format(TEXT("%04d-%02d-%02d %02d:%02d:%02d"), LastAccessTime.wYear
					, LastAccessTime.wMonth, LastAccessTime.wDay, LastAccessTime.wHour, LastAccessTime.wMinute
					, LastAccessTime.wSecond);
				FileTimeToLocalFileTime(&(findData->ftLastWriteTime),&ftTempLastWriteTime);
				FileTimeToSystemTime(&ftTempLastWriteTime, &LastWriteTime);
				strLastWriteTime.Format(TEXT("%04d-%02d-%02d %02d:%02d:%02d"), LastWriteTime.wYear
					, LastWriteTime.wMonth, LastWriteTime.wDay, LastWriteTime.wHour, LastWriteTime.wMinute
					, LastWriteTime.wSecond);
				CString strMD5=_T("");

				CFile File;
				if(File.Open(strfilename, CFile::modeRead | CFile::shareDenyWrite | CFile::typeBinary))
				{									
					strMD5 = CMD5Checksum ::GetMD5(File);

					File.Close();
				}

				char *uid=NULL;
				int ret=0;

				char sql[2048];
				char *errMsg=NULL;
				memset(sql, 0, 2048);
				uid=UnicodeToUtf8(NewGUID());

				_snprintf_s(sql, 2047, "insert into sensitive_file(sensitivefile_id, sensitivefile_name,sensitivefile_md5, sensitivefile_size, sensitivefile_creation_time,sensitivefile_access_time,sensitivefile_lastwrite_time,mac_address, event_task_id) values('%s','%s', '%s', '%s', '%s', '%s',  '%s', '%s','%s')", 
					uid, UnicodeToUtf8(strfilename),UnicodeToUtf8(strMD5), UnicodeToUtf8(strFileSize), UnicodeToUtf8(strCreationTime), UnicodeToUtf8(strLastAccessTime),UnicodeToUtf8(strLastWriteTime),UnicodeToUtf8(CTOOLBOX4App::ms_strMacAddr), UnicodeToUtf8(CModule::m_csEventTaskId));
				ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
				if(ret != SQLITE_OK)
				{
					OutputDebugString(_T("insert err-sensitive_file"));
					OutputDebugString(CString(errMsg));
					sqlite3_free(errMsg);
				}

				if(uid!=NULL)
				{
					delete []uid;
					uid = NULL;
				}

				FindClose(hd);
			}
			myWow64EnableWow64FsRedirection(TRUE);
		}
	}
}
void  myGetFileList(sqlite3 *db)
{
	
	for (vector<CString>::const_iterator itr1 = CTOOLBOX4App::m_SensitivePath.cbegin();itr1 !=  CTOOLBOX4App::m_SensitivePath.cend();itr1++)
	{
		CString strFilePath = *itr1;
		sqlite3_exec(db,"begin;",0,0,0);

		getFileMd5(strFilePath.GetBuffer(),db);
		sqlite3_exec(db,"commit;",0,0,0);
	}
	//sqlite3_close(db);

	
}
//补丁入库
void PathInfoToDB(sqlite3 *db,set<PATHINFOLIST>&PathLists,CString Mac,CString EventID)
{
	int ret;
	char * errMsg = NULL;
	char *Path_Num=NULL;//补丁编号
	char *Path_Name=NULL;//补丁名称
	char *Path_version=NULL;//版本
	char *Path_Program=NULL;//程序
	char *Path_InstallDate=NULL;//安装日期
	char *Path_Publisher=NULL;//发布者
	char *Uid=NULL;
	char sql[1024];
	char *cMac = UnicodeToUtf8(Mac);
	char *cEventid = UnicodeToUtf8(EventID);
	set<PATHINFOLIST>::iterator itPathlists;
	for (itPathlists = PathLists.begin(); itPathlists != PathLists.end(); itPathlists++) 
	{
		Uid=UnicodeToUtf8(NewGUID());
		Path_Num=UnicodeToUtf8(itPathlists->Path_Num);
		Path_Program=UnicodeToUtf8(itPathlists->Path_Program);
		Path_Publisher=UnicodeToUtf8(itPathlists->Path_Publisher);
		Path_version=UnicodeToUtf8(itPathlists->Path_Version);
		Path_Name=UnicodeToUtf8(itPathlists->Path_Name);
		Path_InstallDate=UnicodeToUtf8(itPathlists->Path_InstallDate);
		memset(sql, 0, 1024);
		_snprintf_s(sql, 1023, "insert into path_info(path_id, path_num, path_name, path_program, path_version,path_publisher,path_install_date,mac_address, event_task_id) values('%s', '%s', '%s', '%s', '%s','%s', '%s', '%s', '%s')", 
			Uid, Path_Num, Path_Name, Path_Program,Path_version,Path_Publisher, Path_InstallDate,cMac, cEventid);
		ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
		if(ret != SQLITE_OK)
		{
			OutputDebugString(_T("insert err-path_info"));
			OutputDebugString(CString(errMsg));
			sqlite3_free(errMsg);
		}
		if(Uid != NULL)
		{
			delete []Uid;
			Uid = NULL;
		}
		if(Path_Num != NULL)
		{
			delete []Path_Num;
			Path_Num = NULL;
		}
		if(Path_Name != NULL)
		{
			delete []Path_Name;
			Path_Name = NULL;
		}
		if(Path_Name != NULL)
		{
			delete []Path_Name;
			Path_Name = NULL;
		}
		if(Path_Program != NULL)
		{
			delete []Path_Program;
			Path_Program = NULL;
		}
		if(Path_version != NULL)
		{
			delete []Path_version;
			Path_version = NULL;
		}
		if(Path_Publisher != NULL)
		{
			delete []Path_Publisher;
			Path_Publisher = NULL;
		}
		if(Path_InstallDate != NULL)
		{
			delete []Path_InstallDate;
			Path_InstallDate = NULL;
		}

	}
	if(cMac != NULL)
	{
		delete []cMac;
		cMac = NULL;
	}
	if(cEventid != NULL)
	{
		delete []cEventid;
		cEventid = NULL;
	}

}
void GetClipboardDataToDB(HWND hWnd,sqlite3 *db,CString resultpath,CString Mac,CString EventID)
{
	int ret;
	char * errMsg = NULL;
	char *cMac = UnicodeToUtf8(Mac);
	char *cEventid = UnicodeToUtf8(EventID);
	CString strResultPath;
	char *csResultpath=NULL;
	char sql[512];
	memset(sql,0,512);
	char *cUuid = NULL;
	if(OpenClipboard(hWnd))
	{
		int format=0;
		//	EmptyClipboard();
		UINT clipboard_format;
		HGLOBAL global_memory;
		LPCSTR clipboard_data;
		clipboard_format = EnumClipboardFormats(0);
		if(clipboard_format==13||clipboard_format==1||clipboard_format==49161)
		{
			global_memory = GetClipboardData(CF_TEXT);
			clipboard_data= (LPCSTR)GlobalLock(global_memory);
		}
		else
		{
			global_memory = GetClipboardData(clipboard_format);
			clipboard_data= (LPCSTR)GlobalLock(global_memory);
		}

		if (clipboard_data != NULL) 
		{
			auto data_size = GlobalSize(global_memory);
			std::ofstream ofs;
			if(clipboard_format==49336)
			{
				strResultPath=resultpath+_T("主机层\\ClipboardData.html");
				std::ofstream ofs(resultpath);
				ofs.write(clipboard_data,data_size );
				ofs.close();
			}
			else
			{
				strResultPath=resultpath+_T("主机层\\ClipboardData.txt");
				std::ofstream ofs(strResultPath);
				ofs.write(clipboard_data,data_size );
				ofs.close();
			}
			GlobalUnlock(global_memory);

		
		
		}
	}
	CloseClipboard();
	cUuid = UnicodeToUtf8(NewGUID());
	csResultpath=UnicodeToUtf8(strResultPath);
	_snprintf_s(sql, 511, "insert into clipboard_data(data_id, data_path, mac_address, event_task_id) values('%s', '%s',  '%s', '%s')", 
		cUuid, csResultpath, cMac, cEventid);
	ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
	if(ret != SQLITE_OK)
	{
		OutputDebugString(_T("insert err-Senior_Policy_Audit1"));
		OutputDebugString(CString(errMsg));
		sqlite3_free(errMsg);
	}
	if(cUuid != NULL)
	{
		delete []cUuid;
		cUuid = NULL;
	}
	if(csResultpath!=NULL)
	{
		delete []csResultpath;
		csResultpath = NULL;
	}
	if(cMac != NULL)
	{
		delete []cMac;
		cMac = NULL;
	}
	if(cEventid != NULL)
	{
		delete []cEventid;
		cEventid = NULL;
	}

}
void LocalUserToDB(sqlite3 *db, CString Mac, CString EventID)
{
	char *cMac = UnicodeToUtf8(Mac);
	char *cEventid = UnicodeToUtf8(EventID);
	//CStringArray allUserNam;           //保存所有用户的用户名
//	allUserNam.RemoveAll();
	vector<WCHAR*> pMyUserName;
	char *username=NULL;
	int ret;
	char * errMsg = NULL;
	char *cUuid=NULL;
	char sql[512];
	DWORD Number = GetUserEnumInfo(pMyUserName);
	if (Number)
	{
		vector<WCHAR*>::iterator it = pMyUserName.begin();
		for (; it != pMyUserName.end(); it++)
		{
			CString strUserName = (*it);
			username=UnicodeToUtf8(strUserName);
			cUuid = UnicodeToUtf8(NewGUID());
			memset(sql,0,512);
			_snprintf_s(sql, 511, "insert into local_user_table(username_id, username,  mac_address, event_task_id) values('%s', '%s', '%s',  '%s')", 
				cUuid, username, cMac, cEventid);
			ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
			if(ret != SQLITE_OK)
			{
				OutputDebugString(_T("insert err-Senior_Policy_Audit1"));
				OutputDebugString(CString(errMsg));
				sqlite3_free(errMsg);
			}
			if(cUuid != NULL)
			{
				delete []cUuid;
				cUuid = NULL;
			}
			if(username != NULL)
			{
				delete []username;
				username = NULL;
			}
		
		}
	
		if(cMac != NULL)
		{
			delete []cMac;
			cMac = NULL;
		}
		if(cEventid != NULL)
		{
			delete []cEventid;
			cEventid = NULL;
		}
	}

}
// 本地策略入库
void LocalPolicyAuditToDB(sqlite3 *db, list<ACCOUNTINFO>&info, CString Mac, CString EventID)
{
	int ret;
	char * errMsg = NULL;

	char sql[512];
	CString type = _T("本地策略");
	char *cType = UnicodeToUtf8(type);
	char *cMac = UnicodeToUtf8(Mac);
	char *cEventid = UnicodeToUtf8(EventID);
	list<ACCOUNTINFO>::iterator it;
	char *cItem = NULL;
	char *cValue = NULL;
	char *cUuid = NULL;
	for(it = info.begin(); it != info.end(); it++)
	{
		cUuid = UnicodeToUtf8(NewGUID());
		cItem = UnicodeToUtf8(it->strName);
		cValue = UnicodeToUtf8(it->strValue);
		memset(sql, 0, sizeof(sql));
		_snprintf_s(sql, 511, "insert into Senior_Policy_Audit(id, policy_type, policy_item, policy_values, mac_address, event_task_id) values('%s', '%s', '%s', '%s', '%s', '%s')", 
			cUuid, cType, cItem, cValue, cMac, cEventid);
		ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
		if(ret != SQLITE_OK)
		{
			OutputDebugString(_T("insert err-Senior_Policy_Audit1"));
			OutputDebugString(CString(errMsg));
			sqlite3_free(errMsg);
		}
		if(cUuid != NULL)
		{
			delete []cUuid;
			cUuid = NULL;
		}
		if(cItem != NULL)
		{
			delete []cItem;
			cItem = NULL;
		}
		if(cValue != NULL)
		{
			delete []cValue;
			cValue = NULL;
		}
	}
	if(cType != NULL)
	{
		delete []cType;
		cType = NULL;
	}
	if(cMac != NULL)
	{
		delete []cMac;
		cMac = NULL;
	}
	if(cEventid != NULL)
	{
		delete []cEventid;
		cEventid = NULL;
	}

}

void PolicyToDB(sqlite3 *db, CString Type, CString Item, CString Values,CString Mac, CString EventID)
{
	int ret;
	char * errMsg = NULL;

	char *cMac = UnicodeToUtf8(Mac);
	char *cEventid = UnicodeToUtf8(EventID);
	char *cType = UnicodeToUtf8(Type);
	char *cItem = UnicodeToUtf8(Item);
	char *cValues = UnicodeToUtf8(Values);
	char *uuid = UnicodeToUtf8(NewGUID());

	char sql[512];
	memset(sql, 0, sizeof(sql));
	_snprintf_s(sql, 511, "insert into Senior_Policy_Audit(id, policy_type, policy_item, policy_values, mac_address, event_task_id) values('%s', '%s', '%s', '%s', '%s', '%s')", 
		uuid, cType, cItem, cValues, cMac, cEventid);
	//OutputDebugString(sql);
	ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
	if(ret != SQLITE_OK)
	{
		OutputDebugString(_T("insert err-Senior_Policy_Audit2"));
		OutputDebugString(CString(errMsg));
		sqlite3_free(errMsg);
	}
	DeleteChar(cMac);
	DeleteChar(cEventid);
	DeleteChar(cType);
	DeleteChar(cItem);
	DeleteChar(cValues);
	DeleteChar(uuid);

	return;
}

// 高级策略审核 入库
void SeniorPolicyAuditToDB(sqlite3 *db, CString Mac, CString EventID)
{
	vector<pair<CString, CString>>::iterator it;
	for(it = vtAccountLogin.begin(); it != vtAccountLogin.end(); it++)
	{
		PolicyToDB(db, _T("账户登录"), it->first, it->second, Mac, EventID);
	}
	for(it = vtAccountManage.begin(); it != vtAccountManage.end(); it++)
	{
		PolicyToDB(db, _T("账户管理"), it->first, it->second, Mac, EventID);
	}
	for(it = vtDetailedTrace.begin(); it != vtDetailedTrace.end(); it++)
	{
		PolicyToDB(db, _T("详细跟踪"), it->first, it->second, Mac, EventID);
	}
	for(it = vtDSAccess.begin(); it != vtDSAccess.end(); it++)
	{
		PolicyToDB(db, _T("DS访问"), it->first, it->second, Mac, EventID);
	}
	for(it = vtLoginLogout.begin(); it != vtLoginLogout.end(); it++)
	{
		PolicyToDB(db, _T("登录/注销"), it->first, it->second, Mac, EventID);
	}
	for(it = vtObjectAccess.begin(); it != vtObjectAccess.end(); it++)
	{
		PolicyToDB(db, _T("对象访问"), it->first, it->second, Mac, EventID);
	}
	for(it = vtPolicyChange.begin(); it != vtPolicyChange.end(); it++)
	{
		PolicyToDB(db, _T("策略更改"), it->first, it->second, Mac, EventID);
	}
	for(it = vtPrivilegeUse.begin(); it != vtPrivilegeUse.end(); it++)
	{
		PolicyToDB(db, _T("特权使用"), it->first, it->second, Mac, EventID);
	}
	for(it = vtSystem.begin(); it != vtSystem.end(); it++)
	{
		PolicyToDB(db, _T("系统"), it->first, it->second, Mac, EventID);
	}


}

char* TCHAR2char( const TCHAR* STR )
{
	//返回字符串的长度
	int size = WideCharToMultiByte(CP_ACP, 0, STR, -1, NULL, 0, NULL, FALSE);

	//申请一个多字节的字符串变量
	char* str = new char[sizeof(char) * size];
	memset(str,0,size);
	//将STR转成str
	WideCharToMultiByte(CP_ACP, 0, STR, -1, str, size, NULL, FALSE);
	return str;
}

void WebInfoToDB(sqlite3*db, CString Mac, CString EventId)
{
	vector<WebCollectionInfo>::iterator it = CTOOLBOX4App::msv_WebInfo.begin();
	CString csSql;
	char *cSql = NULL;
	int ret;
	char *errMsg;
	for(;it != CTOOLBOX4App::msv_WebInfo.end(); it++)
	{
		csSql.Format(_T("insert into Web_Collection_Info(id, web_type, web_filesize, web_logsize, mac_address, event_task_id) values('%s', '%s', '%llu', '%llu', '%s', '%s')"), 
			NewGUID(), it->WebType, it->FileSize, it->LogSize, Mac, EventId);
		OutputDebugString(csSql);
		cSql = UnicodeToUtf8(csSql);
		ret = sqlite3_exec(db, cSql, NULL, NULL, &errMsg);
		if(ret != SQLITE_OK)
		{
			OutputDebugString(CString(errMsg));
			OutputDebugString(_T("insert err-Web_Collection_Info"));
			
			sqlite3_free(errMsg);
		}

		delete []cSql;
		cSql = NULL;
	}
	CTOOLBOX4App::msv_WebInfo.clear();
}
// 创建用户+启用用户 日志入库
void GetCreateUserLogToDb(sqlite3*db)
{
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;
	char *cSql;

	// 4720:创建用户, 4722:启用用户
	const char *Sql = "select date,describe from Win_Sec_Log where event_id = '4720' or event_id = '4722'";
	CString insertSql;
	ret = sqlite3_get_table(db, Sql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		CString csFiled;
		CString csValue;
		char* cFiledName = NULL;
		char* cValues = NULL;
		for (i = 0; i < nRow; i++)
		{
			CString UserAccount, Account;
			CString flag = _T("-");
			CString csDate;
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				char * cFiledName = dbResult[j];
				csFiled = UTF82WCS(cFiledName);
				if(csFiled == _T("describe"))
				{
					
					csValue = UTF82WCS(dbResult[index]);

					CString temp;
					BOOL bIsUseAccount = TRUE;

					BOOL bIsNewAccount = FALSE;
					BOOL bIsTgtAccount = FALSE;
					while(!csValue.IsEmpty())
					{
						if(csValue.Find(_T('|')) >= 0)
						{
							temp = csValue.Left(csValue.Find(_T('|')));
							//if(temp.Find(_T("使用者:")) >= 0)
							//	bIsUseAccount = TRUE;
							 if(temp.Find(_T("新帐户:")) >= 0)
								bIsNewAccount = TRUE;
							else if(temp.Find(_T("目标帐户:")) >= 0)//新帐户:
								bIsTgtAccount = TRUE;
							if(bIsUseAccount)
							{
								if(temp.Find(_T("帐户名:")) >= 0)
								{
									UserAccount = temp.Right(temp.GetLength()-temp.Find(_T(':'))-1);
									UserAccount.TrimLeft();
									UserAccount.TrimRight();
									bIsUseAccount = FALSE;
								}
							}
							if(bIsNewAccount)
							{
								flag = _T("0");	// 创建用户
								if(temp.Find(_T("帐户名:")) >= 0)
								{
									Account = temp.Right(temp.GetLength()-temp.Find(_T(':'))-1);
									Account.TrimLeft();
									Account.TrimRight();
									bIsNewAccount = FALSE;
									break;
								}
							}
							if(bIsTgtAccount)
							{
								flag = _T("1");// 启用用户
								if(temp.Find(_T("帐户名:")) >= 0)
								{
									Account = temp.Right(temp.GetLength()-temp.Find(_T(':'))-1);
									Account.TrimLeft();
									Account.TrimRight();
									bIsNewAccount = FALSE;
									break;
								}
							}
							csValue = csValue.Right(csValue.GetLength()-csValue.Find(_T('|'))-1);
						}
					}
				}
				else if(csFiled == _T("date"))
				{
					csDate = UTF82WCS(dbResult[index]);
				}
				index++;
			}
			insertSql.Format(_T("insert into user_analysis(id, ip, username, taget_username, create_time, flag, mac_address, event_task_id) values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')"), NewGUID(), CTOOLBOX4App::ms_strIP, UserAccount, Account, csDate, flag, CTOOLBOX4App::ms_strMacAddr, CModule::m_csEventTaskId);
			cSql = UnicodeToUtf8(insertSql);
			ret = sqlite3_exec(db, cSql, NULL, NULL, &errMsg);
			if(errMsg != NULL)
			{
				MessageBox(NULL, UTF82WCS(errMsg), _T("错误"), MB_ICONERROR);
				OutputDebugString(_T("sqlite3_exec1 error"));
				sqlite3_free(errMsg);
			}
			if(cSql != NULL)
			{
				delete []cSql;
				cSql = NULL;
			}
		}
		sqlite3_free_table(dbResult);
	}
	if(errMsg!=NULL)
		sqlite3_free(errMsg);

}
//获取Win_Sec_Log表个数，如果个数大于0则证明已经采集了主机日志，可以把路径信息写入collection_result_file表中
void CLogAnalyze::HostLogFileInfo(sqlite3 *db)
{
	int nhostLog = 0;
	nhostLog = GetTableCount1(db, "Win_Sec_Log");
	if(nhostLog>0)
	{
		char *cMac = UnicodeToUtf8(CTOOLBOX4App::ms_strMacAddr);
		char *cEventid = UnicodeToUtf8(CModule::m_csEventTaskId);
		char *name=NULL;
		CString strRsFilePath;
		strRsFilePath=CTOOLBOX4App::ms_strFullResultPath+(_T("主机日志"));
		CString strName=_T("主机日志");
		int ret=0;
		name=UnicodeToUtf8(strName);
		char *filepath=NULL;
		filepath=UnicodeToUtf8(strRsFilePath);
		char *uid=NULL;
		char sql[2048];
		char *errMsg=NULL;
		memset(sql, 0, 2048);
		uid=UnicodeToUtf8(NewGUID());

		_snprintf_s(sql, 2047, "insert into collection_result_file(id,name,file_path,mac_address, event_task_id) values('%s','%s', '%s', '%s','%s')", 
			uid, name,filepath,cMac, cEventid);
		ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
		if(ret != SQLITE_OK)
		{
			OutputDebugString(_T("insert plan_tasks"));
			OutputDebugString(CString(errMsg));
			sqlite3_free(errMsg);
		}
		if(uid!=NULL)
		{
			delete []uid;
			uid = NULL;
		}

		if(name!=NULL)
		{
			delete []name;
			name = NULL;
		}
		if(filepath!=NULL)
		{
			delete []filepath;
			filepath = NULL;
		}
		if(cMac != NULL)
		{
			delete []cMac;
			cMac = NULL;
		}
		if(cEventid != NULL)
		{
			delete []cEventid;
			cEventid = NULL;
		}
	}
}
//获取Web_Attack_Action个数，如果个数大于0则证明存在中间日志，这样就可以把路径写入collection_result_file表中
void CLogAnalyze::WebFileInfo(sqlite3 *db)
{
	int nWebAttack = 0;
	nWebAttack = GetTableCount1(db, "Web_Attack_Action");
	if(nWebAttack>0)
	{
		char *cMac = UnicodeToUtf8(CTOOLBOX4App::ms_strMacAddr);
		char *cEventid = UnicodeToUtf8(CModule::m_csEventTaskId);
		char *name=NULL;
		CString strRsFilePath;
		strRsFilePath=CTOOLBOX4App::ms_strFullResultPath+(_T("WebAttackAction"));
		CString strName=_T("web日志");
		int ret=0;
		name=UnicodeToUtf8(strName);
		char *filepath=NULL;
		filepath=UnicodeToUtf8(strRsFilePath);
		char *uid=NULL;
		char sql[2048];
		char *errMsg=NULL;
		memset(sql, 0, 2048);
		uid=UnicodeToUtf8(NewGUID());

		_snprintf_s(sql, 2047, "insert into collection_result_file(id,name,file_path,mac_address, event_task_id) values('%s','%s', '%s', '%s','%s')", 
			uid, name,filepath,cMac, cEventid);
		ret = sqlite3_exec(db, sql, NULL, NULL, &errMsg);
		if(ret != SQLITE_OK)
		{
			OutputDebugString(_T("insert plan_tasks"));
			OutputDebugString(CString(errMsg));
			sqlite3_free(errMsg);
		}
		if(uid!=NULL)
		{
			delete []uid;
			uid = NULL;
		}

		if(name!=NULL)
		{
			delete []name;
			name = NULL;
		}
		if(filepath!=NULL)
		{
			delete []filepath;
			filepath = NULL;
		}
		if(cMac != NULL)
		{
			delete []cMac;
			cMac = NULL;
		}
		if(cEventid != NULL)
		{
			delete []cEventid;
			cEventid = NULL;
		}
	}

}

// 隐藏进程并入库
void CLogAnalyze:: HideProcessToDb(sqlite3*db)
{
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;

	char * cSql = NULL;
	CString csSql;

	const char *Sql = "select DISTINCT name, path, file_md5 from kernel_hidden_process where name not in (select DISTINCT pro_name from Process)";
	ret = sqlite3_get_table(db, Sql, &dbResult, &nRow, &nColumn, &errMsg);
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		CString csField;
		CString csName = _T("");
		CString csPath = _T("");
		CString csMD5 = _T("");
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				csField = UTF82WCS(dbResult[j]);
				if(csField == _T("name"))
					csName = UTF82WCS(dbResult[index]);
				else if(csField == _T("path"))
					csPath = UTF82WCS(dbResult[index]);
				else if(csField == _T("file_md5"))
					csMD5 = UTF82WCS(dbResult[index]);
				index++;
			}
			// 隐藏进程没有进程id
			csSql.Format(_T("insert into hidden_process_analysis(id, ip, prc_name, prc_path, file_md5, mac_address, event_task_id) values('%s', '%s', '%s', '%s', '%s', '%s', '%s')"), 
				NewGUID(), CTOOLBOX4App::ms_strIP, csName, csPath, csMD5, CTOOLBOX4App::ms_strMacAddr, CModule::m_csEventTaskId);
			cSql = UnicodeToUtf8(csSql);
			ret = sqlite3_exec(db, cSql, NULL, NULL, &errMsg);
			if(errMsg != NULL)
			{
				MessageBox(NULL, UTF82WCS(errMsg), _T("错误"), MB_ICONERROR);
				OutputDebugString(_T("sqlite3_exec1 error"));
				sqlite3_free(errMsg);
			}
			EVENT_ASSOCIATION_ANALYSIS eventstruct;
			
			eventstruct.host_ip=CTOOLBOX4App::ms_strIP;
			eventstruct.attack_name=_T("04002");
			eventstruct.file_md5=csMD5;
			eventstruct.process_name=csName;
			eventstruct.file_name=csPath;
			Insertevent_association_analysis(eventstruct,db);
		//	Insertevent_association_analysis(eventstruct,db);
			char *insertsql;

			/*CString strAttackSql;
			CString strAttack_name;
			strAttack_name=_T("04002");

			strAttackSql.Format(_T("insert into event_association_analysis values('%s', '%s', '', '%s', '%s', '%s', '','%s','','','','','','%s','%s','','%s','%s')"),NewGUID(),CTOOLBOX4App::ms_strIP,strAttack_name,_T(""),_T(""),csMD5,csName,csPath,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
			insertsql = UnicodeToUtf8(strAttackSql);
			int ret = sqlite3_exec(db, insertsql, NULL, NULL, &errMsg);
			if(errMsg != NULL)
			{
				if(insertsql != NULL)
				{
					delete []insertsql;
					insertsql = NULL;
				}

				OutputDebugString(_T("event_association_analysis error"));
				sqlite3_free(errMsg);
			}*/
			//2020.11.12分析隐藏进程，并把隐藏进程标识设置为1
			CString updateSql;
			updateSql.Format(_T("UPDATE kernel_hidden_process SET hide_flag='1' WHERE name ='%s'"),csName);
			insertsql = UnicodeToUtf8(updateSql);
			ret = sqlite3_exec(db, insertsql, NULL, NULL, &errMsg);
			if(errMsg != NULL)
			{
				if(insertsql != NULL)
				{
					delete []insertsql;
					insertsql = NULL;
				}

				OutputDebugString(_T("UPDATE kernel_hidden_process error"));
				sqlite3_free(errMsg);
			}
			if(cSql != NULL)
			{
				delete []cSql;
				cSql = NULL;
			}

		}
		sqlite3_free_table(dbResult);
	}
	if(errMsg!=NULL)
		sqlite3_free(errMsg);
}

// 隐藏进程并入库
void CLogAnalyze::HidePortToDb(sqlite3*db)
{
	int ret;
	char ** dbResult = NULL;
	int nRow, nColumn;
	int i, j, index;
	char * errMsg = NULL;
	CString strAttack_name=_T("04001");
	char * cSql = NULL;
	CString csSql;
	CString updateSql;
	CString strport;
	CString strstate;
	const char *Sql = "select DISTINCT port, remote_ip ,state from ports_analysis where port not in (select DISTINCT net_port from Sys_Port_Info)";
	ret = sqlite3_get_table(db, Sql, &dbResult, &nRow, &nColumn, &errMsg);
		EVENT_ASSOCIATION_ANALYSIS eventstruct;
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		CString csField;
		CString strRemoteIP = _T("");
	//	CString csPath = _T("");
	//	CString csMD5 = _T("");
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				csField = UTF82WCS(dbResult[j]);
				if(csField == _T("remote_ip"))
					strRemoteIP = UTF82WCS(dbResult[index]);
				else if(csField==_T("port"))
				{
					strport=UTF82WCS(dbResult[index]);
				}
				else if(csField==_T("state"))
				{
					strstate=UTF82WCS(dbResult[index]);
				}
				index++;
			}
		

			eventstruct.host_ip=CTOOLBOX4App::ms_strIP;
			eventstruct.attack_name=_T("04001");
			eventstruct.attack_ip=strRemoteIP;
			eventstruct.port=strport;
			eventstruct.port_connected_status=strstate;
			Insertevent_association_analysis(eventstruct,db);
			/*csSql.Format(_T("insert into event_association_analysis values('%s', '%s', '%s', '%s', '', '', '','','','','','','','','','','%s','%s')"),NewGUID(),CTOOLBOX4App::ms_strIP,strRemoteIP,strAttack_name,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);



			cSql = UnicodeToUtf8(csSql);
			ret = sqlite3_exec(db, cSql, NULL, NULL, &errMsg);
			if(errMsg != NULL)
			{
				MessageBox(NULL, UTF82WCS(errMsg), _T("错误"), MB_ICONERROR);
				OutputDebugString(_T("sqlite3_exec1 error"));
				sqlite3_free(errMsg);
			}*/
			//2020.11.12分析隐藏网络连接，并把隐藏标识设置为1
			
			updateSql.Format(_T("UPDATE Network SET hide_flag='1' WHERE local_port='%s'"),strport);
			cSql = UnicodeToUtf8(updateSql);
			ret = sqlite3_exec(db, cSql, NULL, NULL, &errMsg);
			if(errMsg != NULL)
			{
				MessageBox(NULL, UTF82WCS(errMsg), _T("错误"), MB_ICONERROR);
				OutputDebugString(_T("Network error"));
				sqlite3_free(errMsg);
			}
			if(cSql != NULL)
			{
				delete []cSql;
				cSql = NULL;
			}

		}
		sqlite3_free_table(dbResult);
	}
	CString GetAttackIPsql;
	const char *SqlIP = "SELECT DISTINCT attack_ip ,host_ip from event_association_analysis where attack_name ='04001'";
	ret = sqlite3_get_table(db, SqlIP, &dbResult, &nRow, &nColumn, &errMsg);
	ATTACKIPANALYSIS attackIP;
	vector<ATTACKIPANALYSIS>attackIPs;
	if(ret == SQLITE_OK)
	{
		index = nColumn;
		CString csField;
		CString strRemoteIP = _T("");
		//	CString csPath = _T("");
		//	CString csMD5 = _T("");
		for (i = 0; i < nRow; i++)
		{
			for (j = 0; j < nColumn; j++)
			{
				//字段名:dbResult[j], 值:dbResult[index];
				csField = UTF82WCS(dbResult[j]);
				if(csField == _T("attack_ip"))
					attackIP.attack_ip = UTF82WCS(dbResult[index]);
				else if(csField==_T("host_ip"))
				{
					attackIP.host_ip=UTF82WCS(dbResult[index]);
				}
				
				index++;
			}
			if(attackIP.attack_ip!=_T("127.0.0.1")&&attackIP.attack_ip!=_T("0.0.0.0")&&attackIP.attack_ip!=attackIP.host_ip)
			{
				attackIP.attack_event_name=_T("04001");
				InsertAttackIpData(attackIP,db);
				//attackIPs.push_back(attackIP);
			}
			
		}
	}
	sqlite3_free_table(dbResult);
	if (errMsg!=NULL)
	{
		sqlite3_free(errMsg);
	}
}


void CLogAnalyze::SynthesisAnalyze(HWND hWnd, int nTaskID, int type, sqlite3*db)
{
	if(CModule::m_bStop)
		return;
	//GetUSN getusn;

	//GetDnsRecord dns;
	ReadKernalResult readKernalRs;
	//WaitForSingleObject(CPage5::m_hSoftWare_custom, INFINITE);
	//WaitForSingleObject(CPage5::m_hSecBaseLine_Custom, INFINITE);
	//WaitForSingleObject(CPage2::m_hSecBaseLine_Fase, INFINITE);
	//WaitForSingleObject(CPage3::m_hSecBaseLine_All, INFINITE);

	// PC资产,中间件类型,检查时间 写xml文件
	OutputDebugString(_T("A0"));
	PC_TimeAndWebType(db);
	OutputDebugString(_T("B0"));
	//////进度信息/////

	// 联网痕迹-深度 结果写xml文件
	//NetDeepRstToXml();
	// 介质痕迹-深度 结果写xml文件
	//UsbDeepRstToXml();
	CString dbName = CTOOLBOX4App::ms_strFullResultPath;
	dbName += _T("主机层\\hongtan004.db");
//	CString dbName= _T("d:\\hongtan004.db");
	//暴力破解
	
  	
//  	sqlite3_exec(db,"begin;",0,0,0);
//  	readKernalRs.Insertviolencecrack(db);
// 	sqlite3_exec(db,"commit;",0,0,0);
	int mTaskId = nTaskID;
	TASKPROGRESS ofX1;
	ofX1.pszText = _T("正在对系统日志进行结果分析...");
	ofX1.nProgress = 51;
	SendMessage(hWnd, WM_RETPROGRESS, (WPARAM)&mTaskId, (LPARAM)&ofX1);
	//////////////////
	// 安全日志入库 // 时间长
	//2020.12.2获取本地用户名并入库local_user_table表中
	LocalUserToDB(db,CTOOLBOX4App::ms_strMacAddr, CModule::m_csEventTaskId);
	//2020.12.2
	LogInsert(); 

	OutputDebugString(_T("C0"));
	//////进度信息/////
	TASKPROGRESS ofAttack;
	ofAttack.pszText = _T("正在进行web攻击事件分析...");
	ofAttack.nProgress = 63;
	SendMessage(hWnd, WM_RETPROGRESS, (WPARAM)&mTaskId, (LPARAM)&ofAttack);
	//获取web层攻击事件信息
	GetAttackInfo();
	//////////////////
	//////进度信息/////
	TASKPROGRESS ofX2;
	ofX2.pszText = _T("正在进行攻击IP分析...");
	ofX2.nProgress = 60;
	SendMessage(hWnd, WM_RETPROGRESS, (WPARAM)&mTaskId, (LPARAM)&ofX2);
	//////////////////
	
	vector<CString> vAttackIp;
	// 获取攻击IP
	GetAttackIp(vAttackIp);
	if(CModule::m_bStop)
		return;
	OutputDebugString(_T("D0"));
	//////进度信息/////
	TASKPROGRESS ofX3;
	ofX3.pszText = _T("正在进行攻击IP时间范围分析...");
	ofX3.nProgress = 67;
	SendMessage(hWnd, WM_RETPROGRESS, (WPARAM)&mTaskId, (LPARAM)&ofX3);
	//////////////////
	// 获取攻击IP的时间范围
	vector<p_IpTimeRange_> vTimeResult;
	GetTimeRange_IP(vAttackIp, vTimeResult);
	
	OutputDebugString(_T("E0"));
	// 从中间件所有日志中确定Ip的时间范围
	GetTimeFromLog(vTimeResult); 

	// ip攻击时所登录的账户 从登录到注销的时间 都判定为此ip的攻击时间
	AttackIp_time(vTimeResult);

	// 攻击IP时间范围入库
	IpTimeInsert(vTimeResult);
	
	if(CModule::m_bStop)
		return;
	//////进度信息/////
	TASKPROGRESS ofX4;
	ofX4.pszText = _T("正在进行结果分析...");
	ofX4.nProgress = 74;
	SendMessage(hWnd, WM_RETPROGRESS, (WPARAM)&mTaskId, (LPARAM)&ofX4);
	//////////////////
	// 筛选已入库安全日志
	//CheckSecEx(vTimeResult);
	OutputDebugString(_T("H0"));
	//////进度信息/////
	TASKPROGRESS ofX5;
	ofX5.pszText = _T("正在对磁盘深度文件进行分析...");
	ofX5.nProgress = 80; 
	SendMessage(hWnd, WM_RETPROGRESS, (WPARAM)&mTaskId, (LPARAM)&ofX5);
	//////////////////
	if(CModule::m_bStop)
		return;

	OutputDebugString(_T("sus01"));
	
	

	// 筛选特权使用日志
	//Privilege();
	///2020.11.20
	
	// 20201031 yl 添加
	// 从安全日志中筛选出创建用户(4720)和启用用户(4722)日志,存入user_analysis表
	GetCreateUserLogToDb(db);

	OutputDebugString(_T("sus02"));
	// 分析可疑账户并入库
	SusAccount(db);
	OutputDebugString(_T("I0"));
	
	// 中间件信息入库
	WebInfoToDB(db, CTOOLBOX4App::ms_strMacAddr, CModule::m_csEventTaskId);
	OutputDebugString(_T("WebInfoToDB"));
	//无文件攻击
	
	CString strFilePath;

	TCHAR szModulPath[MAX_PATH];
	memset(szModulPath, 0, sizeof(szModulPath));
	GetModuleFileName(NULL, szModulPath, MAX_PATH);

	strFilePath=szModulPath;
	//获取logparser.exe路径，主要是为了执行bat脚本传参
	int nIndex ;


	nIndex=strFilePath.ReverseFind(TEXT('\\'));
	if(nIndex)
	{
		strFilePath = strFilePath.Left(nIndex);
		//strBatPath = strBatPath.Left(strBatPath.ReverseFind(_T('\\')));
		strFilePath += TEXT("\\less.ini");
	}
	OutputDebugString(_T("less.ini"));
	
	//web文件篡改
	
	readKernalRs.GetTamperFileInfo(CTOOLBOX4App::m_strWebBackPath,CTOOLBOX4App::m_strWebPath,CTOOLBOX4App::ms_strFullResultPath);
	OutputDebugString(CTOOLBOX4App::m_strWebBackPath);
	OutputDebugString(CTOOLBOX4App::m_strWebPath);
	sqlite3_exec(db,"begin;",0,0,0);
	readKernalRs.InsertTamperTable(db,CTOOLBOX4App::ms_strFullResultPath);
	sqlite3_exec(db,"commit;",0,0,0);
	
	
	nIndex=strFilePath.ReverseFind(TEXT('\\'));
	CString strFile;
	if(nIndex)
	{
		strFilePath = strFilePath.Left(nIndex);
		strFile=strFilePath+TEXT("\\anyfilieupload.ini");
		//strBatPath = strBatPath.Left(strBatPath.ReverseFind(_T('\\')));
		strFilePath += TEXT("\\anyfileup.ini");
	}
	

	sqlite3_exec(db,"begin;",0,0,0);
	readKernalRs.GetAnyFile_Upload(strFilePath,strFile,db);
	sqlite3_exec(db,"commit;",0,0,0);
	//命令行执行
	readKernalRs.GetHostCommand(dbName);
	readKernalRs.InsertHostCommand(db);
// 	//暴力破解
 	readKernalRs.GetPassword_violence_crack(db,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
 	
	//内核结果分析
	sqlite3_exec(db,"begin;",0,0,0);
	readKernalRs.GetFireWallInfo(db);
	sqlite3_exec(db,"commit;",0,0,0);
	readKernalRs.GetOtherRs(db);
	readKernalRs.GetRetweetsPort(db,CTOOLBOX4App::ms_strNetworkIP);
	readKernalRs.ReadKernal(CTOOLBOX4App::ms_strFullResultPath);

	readKernalRs.GetProcessModule(db);
	//readKernalRs.GetTaskList(db);
	//readKernalRs.GetStartupList(db);
	readKernalRs.GetProcessList(db);
	readKernalRs.GetWhiteAndBlackAttack(db);
	//无文件攻击
	nIndex=strFilePath.ReverseFind(TEXT('\\'));
	if(nIndex)
	{
		strFilePath = strFilePath.Left(nIndex);
		//strBatPath = strBatPath.Left(strBatPath.ReverseFind(_T('\\')));
		strFilePath += TEXT("\\less.ini");
	}
	readKernalRs.GetlessFile_Attack(dbName,CTOOLBOX4App::ms_strIP,strFilePath);
	
	// 20201031 yl
	// 隐藏进程入库
	HideProcessToDb(db);
	sqlite3_exec(db,"begin;",0,0,0);
	//隐藏端口网络连接事件入库
	HidePortToDb(db);
	sqlite3_exec(db,"commit;",0,0,0);
	//筛选平台链接
	sqlite3_exec(db,"begin;",0,0,0);
	Screening_Platform_Links(db);
	sqlite3_exec(db,"commit;",0,0,0);
	OutputDebugString(_T("筛选平台链接"));
	// 剪切板
	sqlite3_exec(db,"begin;",0,0,0);
	GetClipboardDataToDB(hWnd,db,CTOOLBOX4App::ms_strFullResultPath,CTOOLBOX4App::ms_strMacAddr,CModule::m_csEventTaskId);
	sqlite3_exec(db,"commit;",0,0,0);
	OutputDebugString(_T("剪切板"));
	//数据库登录日志分析入库
	vector<CString> strDBType;
	 GetdbTyepByPc_Account(db,strDBType);
	 for (int i=0;i<strDBType.size();i++)
	 {
		CString strDbtype;
		strDbtype=strDBType[i];
		InsertDbLog_LogonLog(db,strDbtype);
		//数据库日志登录分析
		vector <CString> vtPrcId;
		GetDbLogUser_violence_crack(db,vtPrcId,strDbtype);
		//分析可疑数据库日志
		
		GetSuspiciousIP(db,strDbtype);
		GetAttackEventByDB(db,strDbtype);
		OutputDebugString(_T("I1"));
	}
	// 磁盘可疑文件深度
	//FileNeep(type, vTimeResult);

	OutputDebugString(_T("J0"));
	if(CModule::m_bStop)
		return;

	//////进度信息/////
	TASKPROGRESS ofX6;
	ofX6.pszText = _T("正在分析攻击工具的分析...");
	ofX6.nProgress = 86;
	SendMessage(hWnd, WM_RETPROGRESS, (WPARAM)&mTaskId, (LPARAM)&ofX6);
	//////////////////

	vector<p_IpTimeRange_>::iterator it;
	for(it = vTimeResult.begin(); it != vTimeResult.end(); it++)
	{
		if(!(*it)->vTime.empty())
		{
			(*it)->vTime.clear();
			vector<CString>().swap((*it)->vTime);
		}
		if(*it != NULL)
		{
			delete *it;
			*it = NULL;
		}
	}
	vTimeResult.clear();

	if(CModule::m_bStop)
		return;

	// 查找IP所对应的攻击工具
	IpTools();
	OutputDebugString(_T("J0-1"));
	//////进度信息/////
	TASKPROGRESS ofX7;
	ofX7.pszText = _T("正在对攻击事件定性...");
	ofX7.nProgress = 90;
	SendMessage(hWnd, WM_RETPROGRESS, (WPARAM)&mTaskId, (LPARAM)&ofX7);
	//////////////////

	// 写Attack_Count表
		//sqlite3_exec(db,"begin;",0,0,0);
	//WebAttackCountInsert();
	//	sqlite3_exec(db,"commit;",0,0,0);
	//写web日志路径collection_result_file
	WebFileInfo(db);
	//写主机日志路径到collection_result_file
	HostLogFileInfo(db);
	CString path = CTOOLBOX4App::ms_strFullResultPath;
	path += _T("主机层\\hongtan004.db");

	// 攻击事件定性及入库
	AttackEventJudgment(path, CTOOLBOX4App::ms_strMacAddr, CTOOLBOX4App::ms_strIP, CModule::m_csEventTaskId);

	OutputDebugString(_T("J0-2"));


	//内核结果大小统计
	CString Kernal = CTOOLBOX4App::ms_strFullResultPath + _T("内核层\\采集结果.ydtxt");
	if(IsFileExist(Kernal))
	{
		CFileStatus fileStatus;
		if(CFile::GetStatus(Kernal, fileStatus))
		{
			CTOOLBOX4App::ms_csKernal.Format(_T("%llu"), fileStatus.m_size);
		}
	}
	//OutputDebugString(_T("7"));
	// 病毒文件个数统计
	CString csVirus = GetTableCount(_T("Virus_Data"));
	CString cstrSql;
	//2020.8.3插入应用日志条数和系统日志条数
	cstrSql.Format(_T("insert into Collection_info(id, sys_log,application_log,host_log, virus_file, kernal_info, file_operation_trace, usb_trace, net_trace, port, process, service, software, file_share, mac_address, event_task_id) values('%s','%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')"), 
		NewGUID(), CTOOLBOX4App::ms_csSysLog,CTOOLBOX4App::ms_csApplicationLog,CTOOLBOX4App::ms_csHostLog, csVirus, CTOOLBOX4App::ms_csKernal, CTOOLBOX4App::ms_csFileTrace,CTOOLBOX4App::ms_csUSBTrace,CTOOLBOX4App::ms_csNetTrace,CTOOLBOX4App::ms_csPort,CTOOLBOX4App::ms_csProcess,CTOOLBOX4App::ms_csService,CTOOLBOX4App::ms_csSoftware,CTOOLBOX4App::ms_csFileShare, CTOOLBOX4App::ms_strMacAddr, CModule::m_csEventTaskId);
	char *cSql2 = UnicodeToUtf8(cstrSql);
	char *errMsg;
	int ret = sqlite3_exec(db, cSql2, NULL, NULL, &errMsg);
	if(ret != SQLITE_OK)
	{
		OutputDebugString(_T("insert err-Collection_info"));
		OutputDebugString(UTF82WCS(errMsg));
		//sqlite3_free(errMsg);
	}
	
	//攻击回溯分析
	MyOutputDebugString(_T("d-"));
	AtackBackAn(path.GetBuffer(), CTOOLBOX4App::ms_strMacAddr.GetBuffer(),CModule::m_csEventTaskId.GetBuffer(), CTOOLBOX4App::ms_strIP.GetBuffer());
	MyOutputDebugString(_T("k-1"));
	OutputDebugString(_T("统计采集数据个数"));
	AnalysisTable(path, CTOOLBOX4App::ms_strMacAddr, CTOOLBOX4App::ms_strIP, CModule::m_csEventTaskId);
	OutputDebugString(_T("根据可疑ip分析web攻击层、主机层"));
	AnalysisSourceIP(path, CTOOLBOX4App::ms_strMacAddr, CTOOLBOX4App::ms_strIP, CModule::m_csEventTaskId);
	/////2020.11.20
	// 获取采集类型
	std::wstring csTemp, csType;
	CString bTime, eTime;
	CString IniFile = CTOOLBOX4App::ms_strFullResultPath;
	IniFile += _T("OriginalCfg.ydini");
	GetIniFileKeyValue(IniFile.GetBuffer(), TEXT("IsStop"), TEXT("isStop"), csTemp);
	if(csTemp.at(0) == _T('F'))
	{
		csType = _T("快速采集");
		CTime t1 = CTime::GetCurrentTime();	// 结束时间是当前时间
		eTime = t1.Format(_T("%Y-%m-%d"));
		t1 -= 30 * 24 * 3600;      // 1个月
		SYSTEMTIME st;
		t1.GetAsSystemTime(st);
		bTime.Format(_T("%04d-%02d-%02d"), st.wYear, st.wMonth, st.wDay); // 开始时间为1个月前
	}
	else if(csTemp.at(0) == _T('A'))
	{
		csType = _T("全盘采集");
		CTime t1 = CTime::GetCurrentTime();	// 结束时间是当前时间
		eTime = t1.Format(_T("%Y-%m-%d"));

		int ret;
		char ** dbResult = NULL;
		int nRow, nColumn;
		int i, j, index;
		char * errMsg = NULL;
		const char * sql = "select install_date from Pc_Account";
		ret = sqlite3_get_table(db, sql, &dbResult, &nRow, &nColumn, &errMsg);
		if(ret == SQLITE_OK)
		{
			index = nColumn;
			for (i = 0; i < nRow; i++)
			{
				for (j = 0; j < nColumn; j++)
				{
					//字段名:dbResult[j], 值:dbResult[index];
					CString str = UTF82WCS(dbResult[index]);
					if(!str.IsEmpty())
					{
						//2019年10月09日14时41分20秒
						CString year = str.Left(str.Find(_T('年')));
						str = str.Mid(str.Find(_T('年'))+1);
						CString month = str.Left(str.Find(_T('月')));
						str = str.Mid(str.Find(_T('月'))+1);
						CString day = str.Left(str.Find(_T('日')));
						bTime.Format(_T("%s-%s-%s"), year, month, day);
					}
					else
						bTime = _T("1970-01-01");
					index++;
				}
			}
			sqlite3_free_table(dbResult);	// 释放结果
		}
		sqlite3_free(errMsg);

	}
	else//C
	{
		csType = _T("自定义采集");
		bTime = CPage4::m_stBegTime.Format(_T("%Y-%m-%d"));
		eTime = CPage4::m_stEndTime.Format(_T("%Y-%m-%d"));
	}

	CString timeRange;
	timeRange.Format(_T("%s -- %s"), bTime.GetBuffer(), eTime.GetBuffer());
	CString csSql;
	csSql.Format(_T("insert into Collection_Mode(id, collection_type, time_range, mac_address, event_task_id) values('%s', '%s', '%s', '%s', '%s')"), 
		NewGUID().GetBuffer(), csType.c_str(), timeRange.GetBuffer(), CTOOLBOX4App::ms_strMacAddr.GetBuffer(), CModule::m_csEventTaskId.GetBuffer());
	char *cSql = UnicodeToUtf8(csSql);
	char *errMsg2;
	int ret2 = sqlite3_exec(db, cSql, NULL, NULL, &errMsg2);
	if(ret2 != SQLITE_OK)
	{
		OutputDebugString(_T("insert err-Collection_Mode!"));
		OutputDebugString(CString(errMsg2));
		sqlite3_free(errMsg2);
	}
	//获取敏感目录文件
	//2020.12.17去掉敏感目录
	//myGetFileList(db);
	//// 获取采集开始时间
	//CString BeginTime;
	//GetIniFileKeyValue(IniFile,TEXT("ExecuteTime"),TEXT("ExecuteTime"),BeginTime);
	//// 获取采集完成时间
	//CString Finish_Time;
	//SYSTEMTIME _st_;
	//GetLocalTime(&_st_);
	//Finish_Time.Format(_T("%04u-%02u-%02u %02u:%02u:%02u"), _st_.wYear, _st_.wMonth, _st_.wDay, _st_.wHour, _st_.wMinute, _st_.wSecond);
	
	CTOOLBOX4App::ms_strMacAddr.ReleaseBuffer();
	CModule::m_csEventTaskId.ReleaseBuffer();
	CTOOLBOX4App::ms_strIP.ReleaseBuffer();
	OutputDebugString(_T("K0"));

	return;
}